【问题标题】:Task.Result waits instead of continue asynchronous operationTask.Result 等待而不是继续异步操作
【发布时间】:2014-02-27 12:59:12
【问题描述】:

我有一个任务应该异步运行但同步运行。

我创建了一个任务:

 var task = Task<int>.Factory.FromAsync(proxy.BeginSaveImage(sp, new AsyncCallback(CompleteSave), state), proxy.EndSaveImage);

 int res =   task.Result;

任务调用异步 WCF 服务。 WCF 服务函数:

 public IAsyncResult BeginSaveImage(statePackage sp, AsyncCallback callback, object state)
    {
        gStatePackage = sp;

        // Create a task to do the work
        var task = Task<int>.Factory.StartNew(this.SaveImage, state);

        return task.ContinueWith(res => callback(task));
    }

我在循环中运行任务。

我的问题是,当我运行它时,它不会并行运行,并且每次调用 task.Results 都会等待任务完成后再继续。

当我将任务代码放入函数 SaveImageProcedure 并从循环中调用它时:

Task.Factory.StartNew(() =>
 {
    SaveImageProcedure(sp);
 });

它异步运行。我不想用另一个异步包装器来包装异步调用。为什么使用 task.Result 的调用不会异步运行,我如何将其更改为运行异步而不像运行异步那样包装它(或者如果它运行异步,不要等待结果并继续操作)?

我不需要任务返回值,也不介意获取它,但代码会继续运行循环中的下一次迭代,而无需等待结果继续。

【问题讨论】:

    标签: c# .net wcf asynchronous task-parallel-library


    【解决方案1】:

    通过阅读Result 字段,您正在等待结果可用。 尝试在Continue 中评估结果,或者使用await

    我希望看起来像(伪代码):

    var task = Task<int>...
    task.ContinueWith(result => {
        if (result != expected) throw new Exception("...");
    });
    

    基本上,如果您正在执行一项任务并且必须获得结果,那么您同步地执行这部分工作流程。 Taskasync 只允许你在等待的时候做其他事情,它们没有任何魔法。

    【讨论】:

    【解决方案2】:

    我建议您阅读我的async introMSDN article on best practices。特别是,使用await 而不是ContinueWithResult

    在服务器端,将工作封装在StartNew 中是没有意义的。如果它只有同步工作要做,它应该只是同步执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 2017-11-14
      • 2019-03-02
      • 1970-01-01
      相关资源
      最近更新 更多