简体   繁体   English

将Action <>传递给异步方法

[英]Passing Action<> into Async Method

I understand in an async method that out and ref can not be used. 我知道在异步方法中,不能使用outref But I am unclear on the consequences of using Action (or delegates). 但是我不清楚使用Action (或委托)的后果。 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. 当您始终await任务时,从程序员的角度来看,代码的工作确实接近于同步代码。 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. 无论如何,您的代码都可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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