How to write C# 5 async?

帅比萌擦擦* 提交于 2019-11-30 18:04:24

问题


I have the following scenario:
When a command is inputted (for test, it's a console application, when it's ready, I hope it will be a WebService) I execute some code, and when further user input is needed, I return to the command interpreter immediately. When the new input is given, I want processing to resume from where I left it. That sounds so much like c#5 async-await pattern, that I decided to give it a try. I was thinking about this:

public void CommandParser()
{
   while(true)
   { 
      string s = Console.ReadLine();
      if (s == "do_something")
         Execute();
      else if (s == "give_parameters")
         SetParameters();
      //... 
   }
}
MySettings input;
public async void Execute()
{
  //do stuff here
  MyResult result = null
  if (/*input needed*/){
     input = new MySetting();
     result = await input.Calculate();
  }
  else { /* fill result synchronously*/}
  //do something with result here

}

public void SetParameters()
{
   if (input!=null)
      input.UseThis("something"); //now it can return from await
}

Now my question is, how to write MySettings.Calculate and MySettings.UseThis? How to return a Task from the first and how to signal readyness from the second? I've tried with many factory methods for Task, but I can't find the right one! Please help!


回答1:


One option is to use TaskCompletionSource<T>. That will build a task for you, and you can call SetResult or SetException on the source, which will signal the task appropriately.

That's what I've used to implement AsyncTaskMethodBuilder<T> for Eduasync - so you can look at that for an example.

You'd need to either set up the TaskCompletionSource beforehand or perform some other coordination so that input.Calculate and UseThis both know about the same object - but then Calculate would just return completionSource.Task, and UseThis would call completionSource.SetResult.

Bear in mind that when you call SetResult, the async method will keep going on a different thread-pool thread if you're using a console app (or web service) - so you'd no doubt want to create a different TaskCompletionSource for the main loop to then use for the next round, as it were.



来源:https://stackoverflow.com/questions/6145246/how-to-write-c-sharp-5-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!