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

后端 未结 1 1164
感情败类
感情败类 2021-02-19 13:13

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.

1条回答
  •  伪装坚强ぢ
    2021-02-19 13:39

    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);
    }
    

    0 讨论(0)
提交回复
热议问题