c# - How Run Multiple UI Actions Asyncronously in Silverlight? -
what have seen
this post shows how asynchronously run multiple tasks , wait of them. here solution:
var thread1 = new thread(() => dosomething(1, 0)); var thread2 = new thread(() => dosomething(2, 3)); thread1.start(); thread2.start(); thread1.join(); thread2.join();
the problem
but seems task non-ui task. have same problem ui task. if want ui-related task in wpf/silverlight should use dispatcher
, tried code:
thread getthread(action action) { return new thread(()=> { application.current.rootvisual.dispatcher.begininvoke(()=> { action(); }); }); }
and how use it:
var thread1=getthread(async ()=>{uiproperty1 = await getuipropertyvaluesfromwebserviceasync1();}); var thread2=getthread(async ()=>{uiproperty2 = await getuipropertyvaluesfromwebserviceasync2();}); thread1.start(); thread2.start();
but throws exception
invalid cross-thread access.
how correct code run multiple ui-related task asynchronously? i'm looking best-practices.
edit #1: why i'm using threads
if use approach:
uiproperty1 = await getuipropertyvaluesfromwebserviceasync1(); // call web service uiproperty2 = await getuipropertyvaluesfromwebserviceasync2(); // call web service
these methods called 1 after , prefer call them @ same time (there more 2 web service calls)
edit #2: why don't use taskex.whenall approach
var task1 = getuipropertyvaluesfromwebserviceasync1(); // call web service var task2 = getuipropertyvaluesfromwebserviceasync2(); // call web service taskex.whenall(task1, task2); // seems line never finishes! uiproperty1 = task1.result; //never reaches line uiproperty2 = task2.result;
there no need threads, if need operate on ui elements. if prefer call both methods @ same time, can use taskex.whenall
microsoft.bcl.async
:
public async void someeventhandler(object sender, eventargs e) { var firstuiproperty = getuiproperty1async(); var seconduiproperty = getuiproperty2async(); await taskex.whenall(firstuiproperty, seconduiproperty); }
Comments
Post a Comment