I have tried the code mentioned in this answer: https://stackoverflow.com/a/27089652/
It works fine and I want to use it for running a PowerShell script in for loop. GUI was freezing initially then I tried the code mentioned in this answer: https://stackoverflow.com/a/35735760/
Now GUI does not freeze while the PowerShell script is running in the background although nothing is updated in the textbox until for loop is complete. I want to see the results updating in real time. Here is the code I am running:
        private async void run_click(object sender, RoutedEventArgs e)
        {
            Text1.Text = "";
            
            await Task.Run(() => PS_Execution(Text1));
        }
        internal async Task PS_Execution(TextBox text)
        {
            PowerShell ps = PowerShell.Create();
            ps.AddScript(script.ToString());
            {
                Collection<PSObject> results = ps.Invoke();
                foreach (PSObject r in results)
                {
                    text.Dispatcher.Invoke(() =>
                    {
                        text.Text += r.ToString();
                    });
                    await Task.Delay(100);
                }                
            }
        }
Maybe I am missing something important. Please help me understand how to solve this problem.
 
    