Reputation: 76
List<Task> tasks = new List<Task>();
tasks.Add(Task.Run(() => functionA()));
tasks.Add(Task.Run(() => functionB()));
tasks.Add(Task.Run(() => functionC()));
function A(){
List<string>lstResult =Get list ();
control.DataSource =lstResult ;
control.Databind();
}
function B(){
List<string>lstResult =Get list ();
control.DataSource =lstResult ;
control.Databind();
}
function C(){
List<string>lstResult =Get list ();
control.DataSource =lstResult ;
control.Databind();
}
Here, I am getting Stack Empty exception because of concurrency Issue. How to solve this one. I came across this one Stack Empty Excetpion but nowhere it is mentioned how to overcome this issue.
Upvotes: 0
Views: 403
Reputation: 131712
You can't modify the UI from another thread, in any operating system. This code can be simplified a lot if async/await
is used and Task.Run
moves inside the functions, eg :
async Task functionA(){
var results= await Task.Run(()=>Getlist1();
control1.DataSource =results ;
control1.Databind();
}
async Task functionB(){
var results= await Task.Run(()=>Getlist2();
control2.DataSource =results ;
control2.Databind();
}
async Task functionC(){
var results= await Task.Run(()=>Getlist3();
control3.DataSource =results ;
control3.Databind();
}
var tasks = await Task.WhenAll( functionA(),
functionB(),
functionC());
await
awaits for an already asynchronous operation to complete without blocking. When that operation completes, it returns execution to the original thread, in this case the UI thread
Upvotes: 3
Reputation: 1453
Your control
object can be accessed by multiple threads at the same time. To solve this issue, you have to use MethodInvoker
like this:
function A(){
List<string> lstResult =Getlist();
Invoke(new MethodInvoker(delegate
{
control.DataSource =lstResult ;
control.Databind();
}));
}
Upvotes: 0