How to get a task NOT to be executed on the UI thread

被刻印的时光 ゝ 提交于 2020-01-01 08:23:23

问题


The following code is a simplification of a code in a real application. The problem below is that a long work will be ran in the UI thread, instead of a background thread.

    void Do()
    {
        Debug.Assert(this.Dispatcher.CheckAccess() == true);
        Task.Factory.StartNew(ShortUIWork, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
    }

    void ShortUIWork()
    {
        Debug.Assert(this.Dispatcher.CheckAccess() == true);
        Task.Factory.StartNew(LongWork, TaskCreationOptions.LongRunning);
    }

    void LongWork()
    {
        Debug.Assert(this.Dispatcher.CheckAccess() == false);
        Thread.Sleep(1000);
    }

So Do() is called normally from UI context. And so is ShortUIWork, as defined by the TaskScheduler. However, LongWork ends up called also in UI thread, which, of course, blocks the UI.

How to ensure that a task is not ran in the UI thread?


回答1:


LongRunning is merely a hint to the TaskScheduler. In the case of the SynchronizationContextTaskScheduler (as returned by TaskScheduler.FromCurrentSynchronizationContext()), it apparently ignores the hint.

On the one hand this seems counterintuitive. After all, if the task is long running, it's unlikely you want it to run on the UI thread. On the other hand, according to MSDN:

LongRunning - Specifies that a task will be a long-running, coarse-grained operation. It provides a hint to the TaskScheduler that oversubscription may be warranted.

Since the UI thread isn't a thread pool thread, no "oversubscription" (thread pool starvation) can occur, so it somewhat makes sense that the hint will have no effect for the SynchronizationContextTaskScheduler.

Regardless, you can work around the issue by switching back to the default task scheduler:

void ShortUIWork()
{
    Debug.Assert(this.Dispatcher.CheckAccess() == true);
    Task.Factory.StartNew(LongWork, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}


来源:https://stackoverflow.com/questions/9748234/how-to-get-a-task-not-to-be-executed-on-the-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!