I have the following job sent to multiple threads for processing from main UI thread.
Upon completion of all jobs, I need to issue a message “Job completed” to let the user know it’s done.
LimitedTaskScheduler scheduler = new LimitedTaskScheduler(4);
TaskFactory factory = new TaskFactory(scheduler);
MessageBox.Show("Job started");
for (int i = 0; i < rows.Length; i++)
{
string tabName = rows[i]["TableName"].ToString();
int nStatus;
factory.StartNew<int>(() =>
{
nStatus = ProcessTable(tabName);
return nStatus;
});
}
MessageBox.Show("Job finished");
In the above code, MessageBox.Show(“Job finished”); is executed immediately after the the tasks are sent, which is wrong.
If I use Task.WaitAll(); it will lock up the main UI thread which I don’t want it to.
My question is what is the best way to display “Job finished” message after all tasks are completed while not locking up the main UI thread?
Thanks in advance.
If you need only to notify users, just create a continuation for the task but pass the
TaskSchedulerwhich you get by the callTaskScheduler.FromCurrentSynchronizationContextin UI thread.This continuation will be executed in UI thread after parent task is completed.