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

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

问题描述

我读过的每篇博文都告诉您如何在 C# 中使用异步方法,但出于某种奇怪的原因从未解释过如何构建您自己的异步方法来使用.所以我现在有这个使用我的方法的代码:

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:

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.

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

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;
}

你可能会发现我的async/await 介绍 很有帮助.

You may find my async/await intro helpful.

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

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