简体   繁体   中英

TaskScheduler.FromCurrentSynchronizationContext exception when called from worker thread

Not quite sure what's going on here -

This bit of code is causing issues as it is first called from the Main thread (verified in Task view in VS) and scheduling the tasks, however when setting a breakpoint in UpdateSearchCache we're now in the worker thread - no longer main!

Subsequent pieces of UI code being called from there fail as they're executed on the worker thread.

Isn't that the whole point of specifying the scheduler? What am I missing?

This code is called when starting our app. It's called from the Bootstrapper of our PRISM app and running on the MainThread .

The SynchronizationContext.Current is NOT null when the Task is started.

var currentScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var ctx = SynchronizationContext.Current;
if (ctx == null)
    throw new NullReferenceException();

Task.Factory
    .StartNew(
        () =>
            SearchHelper.CacheSearchResults(_service.GetData())
    .ContinueWith(result => UpdateCache(result.Result), currentScheduler);

当调用线程上没有同步上下文时, TaskScheduler.FromCurrentSynchronizationContext引发InvalidOperationException ,即SynchronizationContext.Current返回null。

Something really weird is going on here. Try the following approach. It's a workaround, but it also may help to diagnose the problem:

var dispatcher = Dispatcher.CurrentDispatcher;
Debug.Assert(dispatcher == Application.Current.Dispatcher);

Task.Factory
    .StartNew(
        () => SearchHelper.CacheSearchResults(_service.GetData()))
    .ContinueWith(result => 
    { 
        // is the app's dispatcher still the same?

        Debug.Assert(dispatcher == Application.Current.Dispatcher);

        // explicitly use Dispatcher.BeginInvoke, that's what
        // DispatcherSynchronizationContext does behind the scene

        Application.Current.Dispatcher.BeginInvoke(new Action(
            () => UpdateCache(result.Result)));

    }, TaskContinuationOptions.ExecuteSynchronously);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM