扩展方法线程安全吗? [英] Is Extension method thread safe?
本文介绍了扩展方法线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此扩展方法线程安全吗?
Is this Extension method thread safe?
public static class Extensions
{
public static void Raise<T>(this EventHandler<T> handler,
object sender, T args) where T : EventArgs
{
if (handler != null) handler(sender, args);
}
}
还是我需要将其更改为此?
or do I need to change it to this?
public static class Extensions
{
public static void Raise<T>(this EventHandler<T> handler,
object sender, T args) where T : EventArgs
{
var h = handler;
if (h!= null) h(sender, args);
}
}
推荐答案
您发现了一个有趣的循环漏洞,它使所有人绊倒了.不,它不是线程安全的.
You found an interesting loop hole, it tripped everybody up. No, it is not thread-safe.
看起来就像通过方法参数复制了EventHandler<>引用一样,但在运行时不会发生这种情况.扩展方法需要内联,就像常规实例方法一样.实际上,由于它很小,很可能非常被内联.没有副本,您必须自己制作.
While it looks like the EventHandler<> reference is copied through the method argument, this is not what happens at runtime. Extension methods are subject to being inlined, just like a regular instance method. In fact, it is extremely likely to get inlined since it is so small. There's no copy, you have to make one yourself.
这篇关于扩展方法线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文