C# 结束 BeginInvoke 的正确方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/435772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:18:48  来源:igfitidea点击:

The proper way to end a BeginInvoke?

c#lambda

提问by Mike_G

I recently read this thread on MSDN. So I was thinking of using a lambda expression as a way of calling EndInvoke just as a way to make sure everything is nice and tidy. Which would be more correct?

我最近在 MSDN 上阅读了这个线程。所以我在考虑使用 lambda 表达式作为调用 EndInvoke 的一种方式,以确保一切都井井有条。哪个更正确?

example 1:

示例 1:

Action<int> method = DoSomething;

method.BeginInvoke(5, (a)=>{method.EndInvoke(a);}, null);

Example 2:

示例 2:

Action<int> method = DoSomething;

method.BeginInvoke(5, (a)=>
                                  {
                                      Action<int> m = a.AsyncState as Action<int>;
                                      m.EndInvoke(a);
                                  }, method);

采纳答案by Hans Passant

Your 2nd example is slightly more efficient because the "method" delegate instance doesn't have to be captured in the closure. I doubt you'd ever notice.

您的第二个示例效率更高,因为不必在闭包中捕获“方法”委托实例。我怀疑你从来没有注意到。

回答by Boris Callens

You might want to read thisthread on Haacked's blog. Haven't had a chance to test it, but the gist is in one of the last lines:

您可能想在 Haacked 的博客上阅读主题。还没有机会测试它,但要点在最后一行之一:

ThreadPool.QueueUserWorkItem(callback => im.Send(to, from, subject, body));

回答by Marcelo Cantos

I don't know if this was possible way back in Jan '09, but certainly now you can just write this:

我不知道这在 09 年 1 月是否可行,但现在你可以这样写:

method.BeginInvoke(5, method.EndInvoke, null);