Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - Will every 'await' operator result in a state machine?

Please consider the following code:

public async Task<string> GetString()
{
    //Some code here...
    var data = await A();
    //Some more code...
    return data;
}
private async Task<string> A()
{
    //Some code here..
    var data = await B();
    //manipulating data...
    return data;
}
private async Task<string> B()
{
    //Some code here..
    var data = await C();
    //manipulating data...
    return data;
}
private async Task<string> C()
{
    //Some code here..
    var data = await FetchFromDB();
    //manipulating data...
    return data;
}
private async Task<string> FetchFromDB()
{
    return await SOME_HTTP_REQUEST;
}

This code demonstrate a most basic functionality - nested async methods. Will every method get translate into a state machine? Or is the compiler sophisticated enough to generate a more efficient structure? In some of my projects, there are ~20 methods between the UI/WebAPI and the I/O call - does that affect the trade-off between the async-await overhead (such as the state machine) and the non-blocking thread benefits? I mean, if, for example, the overhead of 4 state machines (4 nested async methods) equals to 50ms of blocking I/O (in terms of trade-off), will 20 state machine be equal to longer I/O's delay (250ms)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

await doesn't matter in this case. Each async method will generate a state machine (even if it has no awaits at all).

You can see that with this TryRoslyn example.

If you have cases where a state machine isn't needed, where the method doesn't really need to be async like this one for example:

private async Task<string> D()
{
    var data = await FetchFromDB();
    return data;
}

You can remove the async keyword and the state machine that comes with it:

private Task<string> D()
{
    return FetchFromDB();
}

But otherwise, you actually need the state machine and an async method can't operation without it.

You should note that the overhead is quite small and is usually negligible compared to the resources saved by using async-await. If you realize that's not the case (by testing) you should probably just make that operation synchronous.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...