.net c# Func<Task>及变体做为多播委托异步执行会另开线程的问题
<h1 id="1-问题">1. 问题</h1><p>环境是dotnet8及以前的版本,dotnet9+不知道是否还有这个问题(我猜是一样的)。<br>
如下代码,在多播委托await异步执行时,不会等待委托方法执行完成,它们在新的线程中运行。</p>
<pre><code class="language-csharp">async Task A()
{
}
async Task B()
{
}
Func<Task> func;//下面+=运算赋值为多播委托
func+=async()=>await A();
func+=async()=>await B();
await func();//这里不会等待A和B方法执行完成,它们在新的线程中运行
</code></pre>
<h1 id="2-解决">2. 解决</h1>
<p>用GetInvocationList方法取得所有委托方法,逐个执行。</p>
<pre><code class="language-csharp">Func<Task> func;//下面+=运算赋值为多播委托
func+=async()=>await A();
func+=async()=>await B();
var subscribers = func.GetInvocationList();//取得多播委托的每个方法然后逐个执行
foreach(var subscriber in subscribers)
{
var asyncMethod = (Func<Task>)subscriber;
await asyncMethod();
}
</code></pre>
<h1 id="3-总结">3. 总结</h1>
<p>同样的道理,也适用于事件,因为事件本身也是委托。用这个办法就可以解决事件、委托、Action、Func等同步还是异步执行的问题。</p>
</div>
<div id="MySignature" role="contentinfo">
<div id="AllanboltSignature">
<p id="PSignature" style="border-top-color: #e0e0e0; border-top-width: 1px; border-top-style: dashed; border-right-color: #e0e0e0; border-right-width: 1px; border-right-style: dashed; border-bottom-color: #e0e0e0; border-bottom-width: 1px; border-bottom-style: dashed; border-left-color: #e0e0e0; border-left-width: 1px; border-left-style: dashed; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 80px; background-image: url(https://images.cnblogs.com/cnblogs_com/pains/109838/r_copyright.png); background-attachment: initial; background-origin: initial; background-clip: initial; font-family: 微软雅黑; font-size: 11px; background-color: #e5f1f4; background-position: 1% 50%; background-repeat: no-repeat no-repeat; ">
作者:Rick Carter
<br />
出处:http://pains.cnblogs.com/
<br />
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
</p>
</div><br><br>
来源:https://www.cnblogs.com/pains/p/18854297
頁:
[1]