事件处理程序不是线程安全的?线程、事件、不是、程序

由网友(匿)分享简介:所以,我读过,而不是直接调用的事件周围So i've read around that instead of calling a event directly withif (SomeEvent != null)SomeEvent(this, null);我应该做的。i should be doing Some...

所以,我读过,而不是直接调用的事件周围

So i've read around that instead of calling a event directly with

if (SomeEvent != null)
   SomeEvent(this, null);

我应该做的。

i should be doing

SomeEventHandler temp = SomeEvent;
if (temp != null)
    temp(this, null);

为什么会这样呢?如何在第二个版本成为线程安全的?什么是最好的做法是什么?

Why is this so? How does the second version become thread safe? What is the best practice?

推荐答案

事件是真的语法糖了与会代表的名单。当你调用事件,这实在是迭代的列表,并调用每一个代表与你传递的参数。

Events are really syntactic sugar over a list of delegates. When you invoke the event, this is really iterating over that list and invoking each delegate with the parameters you have passed.

与线程的问题是,他们可以添加或通过订购/退订去除这个集合中的项目。如果他们这样做,而你是遍历集合,这将导致问题(我想抛出一个异常)

The problem with threads is that they could be adding or removing items from this collection by subscribing/unsubscribing. If they do this while you are iterating the collection this will cause problems (I think an exception is thrown)

的意图是该列表复制迭代之前,所以你免受更改到列表中。

The intent is to copy the list before iterating it, so you are protected against changes to the list.

注:然而现在可以为你的听众被调用,即使你退订,所以你应该确保你在你的听众code处理这个问题。

Note: It is however now possible for your listener to be invoked even after you unsubscribed, so you should make sure you handle this in your listener code.

阅读全文

相关推荐

最新文章