c# - Task.Yield(); SyncAction(); vs Task.Run(()=>SyncAction()); -


let's wanted make following method run asynchronously:

resulttype synchronouscode(paramtype x) {      return somelongrunningwebrequest(x); } 

what difference in how following 2 code samples executed/scheduled?

async task<resulttype> asynchronouscode(paramtype x) {     return await task.run(() => somelongrunningwebrequest(x)); } 

compared to:

async task<resulttype> asynchronouscode(paramtype x) {     await task.yield();     return somelongrunningwebrequest(x); } 

i understand task.yield() call ensure thread returns caller, , task.run() schedule code run somewhere on threadpool, both of these methods make method async? let's assume question on default synchronizationcontext.

while both options bad, there difference (important in gui applications): after task.yield returns, rest of method dispatched original synchronizationcontext. if ran ui thread, long running operation executed on ui thread, freezing it. if intention avoid ui blocking - task.yield won't work. task.run won't happen.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -