调用Async WebClient方法停滞

时间:2019-03-23 12:34:45

标签: c# asynchronous async-await

我有以下代码:

public ActionResult DraftScores()
    {
// other code

var json = "";

var fixturesUrl = "someURL";


using (WebClient wc = new WebClient())
{
    wc.Headers.Add("X-Auth-Token", "7d594032xxxxxxxxxxxxxxxxxxxxx");
    json = wc.DownloadString(fixturesUrl);
}

var fixtureList = new JavaScriptSerializer().Deserialize<FixtureList>(json);

model.Matches = fixtureList.matches;

        return View(model);
    }

我试图将其提取到它自己的Async方法中:

    private async Task<List<Match>> GetFixturesAsync()
    {
        var json = "";

        var fixturesUrl = "someURL";

        using (WebClient wc = new WebClient())
        {
            wc.Headers.Add("X-Auth-Token", "7d594032xxxxxxxxxxxxxxxxxxxxx");
            json =  await wc.DownloadStringTaskAsync(fixturesUrl);
        }

        var fixtureList = new JavaScriptSerializer().Deserialize<FixtureList>(json);

        return fixtureList.matches;
    }

呼叫代码:

public ActionResult DraftScores()
    {

//other code

var fixtures = GetFixturesAsync();

   //other code

    model.Matches = fixtures.Result;

        return View(model);
    }

在原始代码中,对 DownloadString 的调用在大约200毫秒内执行。 但是,对 DownloadStringTaskAsync 的调用在几秒钟后仍在运行。我编写该方法的方式有问题吗?

1 个答案:

答案 0 :(得分:2)

要正确执行异步I / O,您需要从控制器到DownloadStringTaskAsync()调用的连续等待链。

第1步,使Action异步。
步骤2,等待异步调用。

public async Task<ActionResult> DraftScores()
{
   ...
   List<Match> result = await GetFixturesAsync();
   ...
}

始终避免使用async void.Result.Wait()

相关问题