【问题标题】:Async methods not running [duplicate]异步方法未运行[重复]
【发布时间】:2017-07-28 16:50:36
【问题描述】:

我正在尝试掌握 async-await 方法,但我真的没有掌握它。我之前用过WebRequest,很简单,可惜是同步的。

我的问题是 StartTest() 没有运行——“因为没有等待这个调用,所以在调用完成之前继续执行当前方法。考虑将'await'运算符应用于调用结果'。我不能在之前添加等待,因为父方法是 Main,它当然不能是异步方法。我意识到我对异步的理解是可怕的——谁能指出我正确的方式?

static void Main(string[] args)
    {
        StartTest();

        async Task<string> StartTest()
        {
            using (var client = new HttpClient())
            {
                List<string> urls = new List<string> { //a list of urls i want to check };

                if (await GetStatusCodes(urls) != true)
                {
                    return "NOT OK";
                }
            }

            return "OK";

        }


        async Task<bool> GetStatusCodes(IList<string> urls)
        {
            using (var client = new HttpClient())
            {
                foreach (var url in urls)
                {
                    var response = await client.GetAsync(url);
                    if (response.StatusCode.ToString() != "OK")
                    {
                        return false;
                    }
                }

                return true;
            }
        }
    }

【问题讨论】:

  • 试试这个:StartTest().GetAwaiter().GetResult();
  • ...或者你可以简单地使用github.com/tejacques/AsyncBridge
  • 我很困惑你为什么把你的方法放在主方法中。
  • @user9993 C#7 在语言中引入了这个特性,它被称为本地函数
  • 我知道,但在这个例子中似乎毫无意义。

标签: c# visual-studio asynchronous async-await


【解决方案1】:

您可以让 MainAsync 方法将您想要异步运行的内容放入其中。

例如

private static void Main()
{
    MainAsync().Wait();
}
private static async Task MainAsync()
{
    // do async stuff
}

【讨论】:

  • .Wait() 不是一个很好的方法,因为异常会被包裹在 AggregateExceptions 中。
  • 这很好用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2016-12-02
  • 2018-02-24
相关资源
最近更新 更多