事件处理程序不是线程安全的? [英] Event handlers not thread safe?

查看:219
本文介绍了事件处理程序不是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于事件处理程序不是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆