My original problem is about UI blocking , what I have is two external process that should execute consecutively with some other codes , every process will be executed n times
, the two execute of these processes cause UI freeze ,
To avoid this problem I've implemented backgroundworker Object in my code , the first process ProcessA will be in a backgroundworker and the second ProcessB will be in the backgroundworker .
Let's start with the ProcessA , when I run my application and start execute the whole task , ProcessA will be running so fast and output results ( I didn't know why it runs quickly) , for the results , they seems correct .
ProcessA executed n steps , every step , it will create a new BackgroundWorker to do the job and execute the task in the background.
The second process must executed after the first process finished , my problem for now is that the event of CompletedTask of the first process won't executed , and the second process start before the first completed .
public void ButtonClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < steps + 1; i++)
{
backgroundworker = new BackgroundWorker();
backgroundworker.DoWork += new DoWorkEventHandler(BackgroundWorker_DoWork);
backgroundworker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
backgroundworker.RunWorkerAsync(Tuple.Create(mypath, i));
}
While(!FirstProcessFinished)
Thread.Sleep(1000);
RunSecondProcess(mypath);
}
protected void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Some code to run first Process
}
protected void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Counter++;
IncrementProgressBar();
Thread.Sleep();
Console.WriteLine("Finished");
if (counter == Steps + 1)
{
FirstProcessFinished = true;
}
}
How can I execute ProcessB correctly after calling n times the backgroundWorker_Completed
?
Update :
I've test the solution of the Orace answer , but now I can't execute the second task and the first task won't complete the process:
private async void Work(string path)
{
try
{
// start all A tasks
var aTasks = new List<Task>();
for (int i = 0; i < steps; i++)
{
aTasks.Add(new Task(() => RunA(path, i)));
}
// wait for them to end
await Task.WhenAll(aTasks);
IncrementProgressBar();
// start B task (it will not be allowed to update the UI)
await Task.Run(() => RunB(path));
IncrementProgressBar();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private async Task RunA(string path, int index)
{
// start the actual work (new task to not freeze the UI)
await Task.Run(() => WorkA(path, index));
// here we are back on the UI thread so we can update the status
IncrementProgressBar();
Console.WriteLine($"Task A{index:00} Finished");
}
What's the wrong here???