I am learning how Task works. I have always used the BackgroundWorker class or the
Threading.Thread class so I wanted to taste Task Factory.
In the following example I am building, I recover a
Task<List<People>>
And assign it a “ContinueWith” that I expect to be called when the task has finished.
I have done some previous examples that were working awesome but this one freeze my
Main form UI when the application is launched. (I can not see difference with the
other examples I did who doesn’t).
Do you know guys why my Main UI freezes?
PS: I know I declare
System.Threading.Tasks.TaskScheduler scheUI
on the Task declaration. I’m not using right now but I will later.
Thanks in advance:
Here is the code:
private void PopulateList(List<People> list)
{
if (listBox1.InvokeRequired)
{
listBox1.Invoke((MethodInvoker) delegate {
foreach (People item in list)
{
listBox1.Items.Add(item.name + " " + listBox1.Items.Add(item.surname));
}
});
}
}
private Task<List<People>> GetPeopleListAsync(int PeopleNuber, int delaysecs)
{
TaskScheduler scheUI = TaskScheduler.FromCurrentSynchronizationContext();
return Task<List<People>>.Factory.StartNew( () =>
{
List<People> listado = new List<People>();
for (int i = 0; i < PeopleNuber; i++)
{
People people = new People
{
name = "Name" + i.ToString(),
surname = "Surname " + i.ToString()
};
Thread.Sleep(delaysecs * 200);
listado.Add(people);
}
return listado;
},CancellationToken.None,
TaskCreationOptions.None,scheUI);
}
void Form1_Load(object sender, EventArgs e)
{
Task<List<People>> task = GetPeopleListAsync(5, 10);
task.ContinueWith(p => PopulateList(task.Result));
}
You are synchronizing the first task with the UI thread using:
Remove the scheUI scheduler from the first task:
You should add the synchronization to the second task that is executed in order to update your UI: