Reputation: 215
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.
Upvotes: 15
Views: 8399
Reputation: 6882
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.
Upvotes: 27
Reputation: 120480
You don't need to start the Tasks returned by async method calls. They're started by default.
Upvotes: 9