语法在C#中,实施了多个异步任务 [英] Syntax for launching many async tasks in c#

查看:269
本文介绍了语法在C#中,实施了多个异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是新的异步遇到了麻烦/等待在C#中的工具。这里是我的情况:

 静态异步任务<布尔> ManageSomeRemoteTask(IN​​T标识,布尔标志)
{
    VAR的结果=等待serviceClient.AuthenticateIdAsync(ID);
    [...设置一些数据...]
    等待serviceClient.LongAndSlowRemoteCallAsync(数据);
}静态无效SendATo​​nOfJunkToSomeWebServiceThatDoesntSupportBatches
{
    VAR myTasks =字典< INT,任务<布尔>>();
    而(IdsLeftToProcess大于0)
    {
      任务<布尔> T = ManageSomeRemoteTask(ID,真实);
      myTasks.Add(IdsLeftToProcess,T);
      myTasks [IdsLeftToProcess]。开始();
      IdsLeftToProcess - ;
    }    Task.WaitAll(myTasks.Values​​.ToArray()); //等待,直到他们全部完成
    [...报告统计...]
}

我在这1问题,当我尝试运行这一点,我得到一个InvalidOperationException上的开始(),并显示错误消息开始可能不会被要求承诺式的任务。这错误消息似乎并没有拿出在谷歌或冰,所以我不知道这意味着什么。这是我的头号关注,如何得到这个运行。我也试过TaskFactory.StartNew(),但不知道如何将参数传递给我的方法的方式。


解决方案
通过异步方法返回

任务总是的,即它们是在运行状态下创建。尝试从您删除task.Start()code - 这应该修复它。

Toub的异步/等待FAQ 一个报价:


  

我是否需要开始的标记为异步?

方法创建的任务
  
  

    

没有。从TAP方法返回的任务是热,意思是任务重是已经在建present操作。你不仅不需要调用。开始()这样的任务,但如果您尝试这样做将失败。有关详细信息,请参见常见问题解答Task.Start。


  

I'm having trouble using the new async/await tools in c#. Here is my scenario:

static async Task<bool> ManageSomeRemoteTask(int Id, bool flag)
{
    var result = await serviceClient.AuthenticateIdAsync(Id);
    [... Setup Some Data ...]
    await serviceClient.LongAndSlowRemoteCallAsync(Data);
}

static void SendATonOfJunkToSomeWebServiceThatDoesntSupportBatches
{
    var myTasks = Dictionary<int, Task<bool>>();
    while(IdsLeftToProcess > 0 )
    {
      Task<bool> t = ManageSomeRemoteTask(Id, true);
      myTasks.Add(IdsLeftToProcess ,t);
      myTasks[IdsLeftToProcess].Start();
      IdsLeftToProcess --;
    }

    Task.WaitAll(myTasks.Values.ToArray()); //Wait until they are all done
    [... Report statistics ...]
}

I have 1 problem in that when I try running this, I get an InvalidOperationException on the Start() with the error message "Start may not be called on a promise-style task." This error message doesn't seem to come up in Google or Bing so I'm not sure what it means. This is my number one concern, how to get this to run. I also tried TaskFactory.StartNew() but didn't understand how to pass parameters to my method that way.

解决方案

Tasks returned by async methods are always hot i.e. they are created in Running state. Try to remove task.Start() from you code - it should fix it.

A quote from Stephen Toub's Async/Await FAQ:

Do I need to "Start" Tasks created by methods marked as "async"?

No. Tasks returned from TAP methods are "hot", meaning the tasks represent operations that are already in-progress. Not only do you not need to call ".Start()" on such tasks, but doing so will fail if you try. For more details, see FAQ on Task.Start.

这篇关于语法在C#中,实施了多个异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆