簡體   English   中英

具有異步操作的異步控制器不起作用

[英]async Controller with async Action doesn't work

我有一個具有異步操作的異步控制器。 在該操作中,我在SomeMethodOne中調用WCF服務方法(返回結果需要10秒),然后在SomeMethodTwo中執行一些數學運算(在我的計算機上執行大約6秒)。 據我了解,在等待WCF服務方法的結果期間,我的計算機應執行SomeMethodTwo,但不會,並且所有代碼都將執行10秒+ 6秒= 16秒。 為什么?

public class TestController : AsyncController
{
    public async Task<ActionResult> Index()
    {
        string result =  await SomeMethodOne();

        SomeMethodTwo();

        return View();
    }

    private async Task<string> SomeMethodOne() // it needs 10 seconds to return result from WCF service
    {
        using (Service1Client client = new Service1Client())
        {
            return await client.GetDataAsync(5);
        }
    }

    private void SomeMethodTwo() // it executes about 6 seconds on my computer
    {
        double result = 0;
        for (int i = 0; i < 1000000000; i++)
        {
            result += Math.Sqrt(i);
        }
    }
}

我在本地運行的WCF服務:

public class Service1 : IService1
{
    public string GetData(int value)
    {
        Thread.Sleep(10000);
        return string.Format("You entered: {0}", value);
    }        
}

您的問題是您正在立即使用await

string result =  await SomeMethodOne();

await意味着您的控制器操作將在繼續執行之前“異步等待”(等待) SomeMethodOne的結果。

如果要進行異步並發,請不要立即await 相反,您可以通過調用方法來啟動異步操作,然后再await

public async Task<ActionResult> Index()
{
  Task<string> firstOperation = SomeMethodOne();

  SomeMethodTwo();

  string result = await firstOperation;

  return View();
}

然后我執行[強調我的]

只要將兩者加在一起, 要做一件事然后再做另一件事。

同時執行兩項操作可能會更快。 由於上下文切換,它可能會變慢(想象某人做了很多“多任務”,並且在它們之間切換的時間比工作要多)。 如果您不必為了執行第二個操作而從第一個操作中獲取結果,那么在這里可能會更快一些:

public async Task<ActionResult> Index()
{
    Task<string> task =  SomeMethodOne();

    SomeMethodTwo();

    string result = await task;

    return View();
}

顯然,如果在調用SomeMethodTwo()之前需要result ,那么將不可能。 await SomeMethodOne() (如果可能與.NET約定相適應,則應稱為SomeMethodOneAsync()仍然有一個優勢,即如果GetDataAsync()是真正異步的,則執行此操作方法的線程可以執行某些操作否則將向Web應用程序發出其他請求,並且當I / O操作返回數據時,另一個線程將繼續處理該請求。 這不利於所涉及的單個方法的性能,但確實有助於針對所有Web請求在計算機上運行的所有方法的整體可伸縮性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM