如何创建在C#中的异步方法? [英] How do you create an asynchronous method in C#?

查看:108
本文介绍了如何创建在C#中的异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每一个博客文章我读过告诉您如何消耗在C#中的异步方法,但对于一些奇怪的原因从来没有解释如何构建自己的异步方法消耗。所以我有这个code现在消耗我的方法:

Every blog post I've read tells you how to consume an asynchronous method in C#, but for some odd reason never explain how to build your own asynchronous methods to consume. So I have this code right now that consumes my method:

private async void button1_Click(object sender, EventArgs e)
{
    var now = await CountToAsync(1000);
    label1.Text = now.ToString();
}

和我写的这个方法就是 CountToAsync

And I wrote this method that is CountToAsync:

private Task<DateTime> CountToAsync(int num = 1000)
{
    return Task.Factory.StartNew(() =>
    {
        for (int i = 0; i < num; i++)
        {
            Console.WriteLine("#{0}", i);
        }
    }).ContinueWith(x => DateTime.Now);
}

是这样的,使用 Task.Factory ,最好的方法写一个异步方法,或者我应该写这个法子?

Is this, the use of Task.Factory, the best way to write an asynchronous method, or should I write this another way?

推荐答案

我不建议 StartNew 除非你需要复杂的那个级别。

I don't recommend StartNew unless you need that level of complexity.

如果您的异步方法是依赖于其他异步方法,最简单的方法是使用异步关键字:

If your async method is dependent on other async methods, the easiest approach is to use the async keyword:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  for (int i = 0; i < num; i++)
  {
    await Task.Delay(TimeSpan.FromSeconds(1));
  }

  return DateTime.Now;
}

如果您的异步方法是做CPU的工作,你应该使用 Task.Run

If your async method is doing CPU work, you should use Task.Run:

private static async Task<DateTime> CountToAsync(int num = 10)
{
  await Task.Run(() => ...);
  return DateTime.Now;
}

您可能会发现我的<一个href=\"http://blog.stephencleary.com/2012/02/async-and-await.html\"><$c$c>async/<$c$c>await介绍有帮助的。

You may find my async/await intro helpful.

这篇关于如何创建在C#中的异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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