c# - Task.ContinueWith callback thread -


i tried find answer couldn't. wondering on thread task.continuewith delegate called. await know tries run on captured synchronizationcontext there nothing documented continuewith.

i tried sample program , though seems called on threadpool thread, suspect in scenario might call on synchronizationcontext. maybe can provide definitive answer.

this depends on scheduler associated continuation. default, task continuations scheduled through current scheduler, being taskscheduler associated executing task. when continuewith not called within task, current return default scheduler, default taskscheduler instance provided .net framework, , schedule tasks on thread pool.

if want influence behaviour, can call 1 of continuewith overloads takes taskscheduler parameter. common pattern pass taskscheduler.fromcurrentsynchronizationcontext() when creating continuations on ui thread, cause continuation dispatched onto ui thread when executed.

edit: in reply your comment: deadlock may arise if spawn child task (intended run on thread pool) continuation running on ui thread. in such cases, child task inherit task scheduler parent task, bound ui thread, causing child task run on ui thread too.

task.factory.startnew(() => {     // background work. }).continuewith(_ => {     // update ui, spawn child task more background work...     task.factory.startnew(() =>     {         // ...but child task runs on ui thread!     }); },     cancellationtoken.none,     taskcontinuationoptions.none,     taskscheduler.fromcurrentsynchronizationcontext()); 

to resolve this, can use startnew overload accepts taskscheduler parameter child task, , pass taskscheduler.default it:

    // update ui, spawn child task more background work...     task.factory.startnew(() =>     {         // ...and child task runs on thread pool.     },         cancellationtoken.none,         taskcreationoptions.none,         taskscheduler.default); 

Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -