正确启动后台线程上的任务

时间:2016-12-01 17:26:33

标签: c# .net multithreading asynchronous task

我正在尝试在后台线程上正确启动返回的Task,以免阻塞UI线程。

阻塞调用在另一个类中完成:

var tcs = new TaskCompletionSource<T>();
request.BeginGetResponse(() => DoSomethingSlowThenCompleteTCS(tcs));
return tcs.Task;

我认为我可以简单地开始这项任务(或者我尝试过的其他一百万种变体:

CallThatReturnsTask()
    .ContinueWith(
        x =>
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new System.Action(() =>
                {
                    // Some continuation stuff that needs to be on the dispatcher
                }
))).Start();

base.OnActivate(); // Call that needs to run immediately

但是我发现我需要将返回的任务包装在Task.Run()中,以便不阻止UI线程。我几乎100%肯定这样做会首先击败返回任务的目的,但这是我让它工作的唯一方法。

Task.Run(() =>
    {
        CallThatReturnsTask()
            .ContinueWith(
                x =>
                    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                        new System.Action(() =>
                        {
                            // Some continuation stuff that needs to be on the dispatcher
                        }
        )));
});

base.OnActivate(); // Call that needs to run immediately

正确的方法是什么?

提前致谢。

--------------------编辑1 --------------------

这样更好吗?看起来好像我在一个任务中包装一个任务,而不是仅仅在正确的线程上执行第一个任务。

Task.Run(() => {
    var result = CallThatReturnsTask().Result;

    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new System.Action(() =>
        {
            // Dispatcher stuff
        }
    ));
});

0 个答案:

没有答案
相关问题