简体   繁体   English

如何在没有新线程或异步和等待关键字但仅任务的情况下获得异步

[英]How to get asynchronousy without new threads or async and await keywords but only Task

I wonder how to accomplish the same thing the below program does without using extra threads or await and async keywords but only Tasks. 我想知道如何在不使用额外线程或awaitasync关键字但仅使用Task的情况下完成以下程序的相同操作。 A sample code would be awesome. 一个示例代码会很棒。 It seems to me that we need to use TaskCompletionSource and Async versions of the IO-bound operations or any long-running operations. 在我看来,我们需要使用IO绑定操作或任何长时间运行的操作的TaskCompletionSourceAsync版本。

static void Main(string[] args)
{
  Task t = Go();
  Console.WriteLine("Hello World");
  Task.Delay(1000).GetAwaiter().OnCompleted(() => { Console.WriteLine("Completed"); });
  Console.ReadLine();
}

static async Task Go()
{
  var task = PrintAnswerToLife();
  await task;
  Console.WriteLine("Done");
}

static async Task PrintAnswerToLife()
{
  var task = GetAnswerToLife();
  int answer = await task;
  Console.WriteLine(answer);
}

static async Task<int> GetAnswerToLife()
{
  var task = Task.Delay(2000);
  await task;
  int answer = 21 * 2;
  return answer;
}

You can do a pretty straightforward translation of async / await into Task by using ContinueWith . 您可以使用ContinueWithasync / await转换为Task ,非常简单。 Other translations are also possible, eg, Task.Delay becomes System.Threading.Timer . 其他翻译也是可能的,例如Task.Delay变为System.Threading.Timer

The basic pattern is, for any async method that does an await : 基本模式是,对于执行await任何async方法:

static async Task Go()
{
  var task = PrintAnswerToLife();
  await task;
  Console.WriteLine("Done");
}

becomes: 变为:

static Task Go()
{
  var tcs = new TaskCompletionSource<object>();
  var task = PrintAnswerToLife();
  task.ContinueWith(_ =>
  {
    Console.WriteLine("Done");
    tcs.SetResult(null);
  });
  return tcs.Task;
}

Correct error handling is a lot more work. 正确的错误处理还有很多工作要做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM