簡體   English   中英

調用非異步方法

[英]Calling non-async methods

有一個 class 庫,它使用 DbContext 從 sql 返回結果。 如果我想建立一個

Class 庫方法可能需要幾秒鍾。 這個 class 在其啟動中被注入到 asp.net 核心 webapp

class Util
{

    public string DoStuff(string colorVal) {

        string ourValue = (from a in ctx.BigTable where a.color == colorVal select a.DoneFlag).FirstOrDefault();

        return ourValue;

    }
}

如果我打算從這樣的代碼中使用它,我是否也需要使這個方法異步

Web project

        Util o;

        public async Task<IViewComponentResult> InvokeAsync()
        {
            var item = await GetMatchingColorAsync();
            return View(item);
        }

        private Task<string> GetMatchingColorAsync()
        {
            string matchingColor = o.DoStuff("red");            
            return Task.FromResult(matchingColor);
        }

理想情況下是的。 您甚至可以在使用FirstOrDefaultAsync時使用它(取決於您的基礎數據源是什么):

public async Task<string> DoStuff(string colorVal) {

    string ourValue = await (from a in ctx.BigTable where a.color == colorVal select a.DoneFlag).FirstOrDefaultAsync();

    var someColor = await GetMatchingColorAsync();

    return ourValue;

}

Microsoft 有一系列關於使用 async 和 await 進行異步編程的文章寫得非常好。 他們值得一讀。

如果您絕對不能更改調用方法,那么您可以同步等待:

public string DoStuff(string colorVal) {

    string ourValue = (from a in ctx.BigTable where a.color == colorVal select a.DoneFlag).FirstOrDefault();

    var someColor = GetMatchingColorAsync().GetAwaiter().GetResult();

    return ourValue;

}

容易吧? 除非它阻塞線程(您失去了異步方法的好處)並且您有死鎖的風險,如本文所述: 不要阻塞異步代碼

那很糟糕™

暫無
暫無

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

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