简体   繁体   中英

Calling non-async methods

Have a class library that makes use of a DbContext to return results from sql. If I want to build a

Class library method that might take a few seconds. This class is injected into an asp.net core webapp in its Startup

class Util
{

    public string DoStuff(string colorVal) {

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

        return ourValue;

    }
}

Do I need to make this method async also if I intend to use it from code like this

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

Ideally yes. You could even use FirstOrDefaultAsync while you're at it (depending on what your underlying data source is):

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 has a series of articles about Asynchronous programming with async and await that are quite well written. They're worth the read.

If you absolutely can't change the calling methods, then you could just synchronously wait:

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;

}

Easy right? Except it blocks the thread (you lose the benefit of the asynchronous methods) and you risk deadlocking, as explained in this article: Don't Block on Async Code .

That's Bad™

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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