相关疑难解决方法(0)

C#事件和线程安全

UPDATE

从C#6开始,这个问题的答案是:

SomeEvent?.Invoke(this, e);
Run Code Online (Sandbox Code Playgroud)

我经常听到/阅读以下建议:

在检查事件之前,请务必复制事件null并将其触发.这将消除线程的潜在问题,其中事件变为null位于您检查null和触发事件的位置之间的位置:

// Copy the event delegate before checking/calling
EventHandler copy = TheEvent;

if (copy != null)
    copy(this, EventArgs.Empty); // Call any handlers on the copied list
Run Code Online (Sandbox Code Playgroud)

更新:我从阅读中了解到这可能还需要事件成员的优化,但Jon Skeet在他的回答中指出CLR不会优化副本.

但同时,为了解决这个问题,另一个线程必须做到这样的事情:

// Better delist from event - don't want our handler called from now on:
otherObject.TheEvent -= OnTheEvent;
// Good, now we can be certain that OnTheEvent will not run...
Run Code Online (Sandbox Code Playgroud)

实际的顺序可能是这种混合物:

// Copy the event delegate before checking/calling
EventHandler copy …
Run Code Online (Sandbox Code Playgroud)

c# events multithreading

230
推荐指数
6
解决办法
8万
查看次数

我可以使用null条件运算符而不是经典事件提升模式吗?

C#6.0添加了这个新的?.运算符,现在允许调用这样的事件:

someEvent?.Invoke(sender, args);
Run Code Online (Sandbox Code Playgroud)

现在,根据我的阅读,这个运算符保证someEvent被评估一次.使用这种调用而不是经典模式是否正确:

var copy = someEvent

if(copy != null)
  copy(sender, args)
Run Code Online (Sandbox Code Playgroud)

我知道某些情况下上面版本的模式需要额外的锁,但让我们假设最简单的情况.

.net c# events c#-6.0

7
推荐指数
1
解决办法
400
查看次数

标签 统计

c# ×2

events ×2

.net ×1

c#-6.0 ×1

multithreading ×1