简体   繁体   English

调用 Async WebClient 方法停止

[英]Call to Async WebClient method stalling

I have the following piece of code:我有以下一段代码:

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

I tried to extract this into it's own Async method:我试图将其提取到它自己的 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;
    }

calling code:调用代码:

public ActionResult DraftScores()
    {

//other code

var fixtures = GetFixturesAsync();

   //other code

    model.Matches = fixtures.Result;

        return View(model);
    }

In the original code the call to DownloadString executes in about 200ms.在原始代码中,对DownloadString的调用在大约 200 毫秒内执行。 However the call to DownloadStringTaskAsync is still running after several seconds.但是,对DownloadStringTaskAsync的调用在几秒钟后仍在运行。 Is there something wrong with the way that I have written the method?我编写方法的方式有问题吗?

To do async I/O properly, you need an unbroken await chain from your Controller to the DownloadStringTaskAsync() call.要正确执行异步 I/O,您需要从控制器到 DownloadStringTaskAsync() 调用的完整等待链。

Step 1, make the Action async.第 1 步,使 Action 异步。
Step 2, await the async call.第 2 步,等待异步调用。

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

Always avoid async void , .Result and .Wait()始终避免async void , .Result.Wait()

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

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