简体   繁体   中英

Assumptions on event raising

Imagine the following class:

class A
{
     public event EventHandler AnyEvent;
}

You create an instance of class A , and attach some event handlers. Now if AnyEvent gets raised, I would not assume, that the event handlers are performed on another thread, than the thread I created the object. This would be of prime importance, if you created the object on a GUI thread, and the event handler performs operations on GUI elements. This would force me to use appropriate invocation patterns.

It really becomes evil, if you use interfaces defining events:

interface B
{
     event EventHandler SomeEvent;
}

Now one implementation could raise the event from the original thread, the next from a second thread. This can cause your application to successfully work with the one, and fail with the other implementation.

I think coding should always be transparent - this is not! And if I don't create another thread, I do not assume, that my methods are performed from any other than my home thread.

Are there any aspects I did not consider? Any that would invalidate my assumption?

There is no magic with events. Events are handled on the thread that raises them. It has nothing to do with the thread that creates the object.

Threading is the responsibility the consumer of the class, not the writer of the class, so your assumption is incorrect.

One should assume a class is not thread-safe unless it is documented to be thread-safe. Even most built-in .NET classes are not thread safe unless they say they are.

It is up to the consumer of the class to be aware of threading.

Calling events is just calling some method (or collection of methods) using a mechanism such as function pointers.

Events are completely oblivious to the thread that attached them, and don't have any other information that could lead to properly Invoking the methods on the right thread.

Maybe you are drawing your assumptions from COM days?

事件的处理程序回调在引发事件的同一线程上。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM