在任务中嵌套任务,试图不阻止UI线程

时间:2014-09-18 08:40:11

标签: c# multithreading .net-4.0 ui-thread

所以我有一个发送服务调用的任务......这个任务有一个continue,这样当调用返回时,程序可以对数据进行排序。现在我也希望当调用返回数据时,它会根据该数据进行另一个服务调用,而不会阻塞UI线程。这可能吗?

到目前为止我的示例代码是:

 Task t = new Task(() =>{//Make my service call};
 t.Start();
 t.ContinueWith((sender) =>
 {
     //sort my data out
     //when thats done make another service call based on that data that doesn't
     // block UI thread
 }, cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

1 个答案:

答案 0 :(得分:0)

如果有人想要了解如何执行此操作的更多信息:

void MyMethod()
{
    Task t = new Task(() =>{//Make my service call};
    t.Start();
    t.ContinueWith((sender) =>
    {
        //sort my data out
        //when thats done make another service call based on that data that doesn't
        // block UI thread

        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += bw_DoWork;
        bw.RunWorkerAsync();
    }, cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
     //do some stuff
}

这个免费的电子书 - Threading in C# by Joseph Albahari帮助了很多