简体   繁体   中英

Passing Action<> into Async Method

I understand in an async method that out and ref can not be used. But I am unclear on the consequences of using Action (or delegates). While I recognize that the value being set in the Action may not be available until after the await, are there any other problems with the below? Are their threading problems? I have googled extensively on this, but can't find clarity anywhere.

protected async Task<gPeriod> MapPeriod(string value, Action<int> setOutput)
{
    (...) //omitted code
    int x = await MyMethodAsync(value)
    setOutput(x);
    return gPeriod;  //calculation of this not shown in this example
}

When you always await a task, code from programmers point of view works really close to synchronous code. But when you start doing things like this

var task1 = FooAsync(setOutput);
var task2 = BarAsync(setOutput);
var result1 = await task1;
var result2 = await task2;

things start to get funny, because order they finish or threads they use is not guaranteed.

Anyway your code is fine.

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