在事件处理程序使用null检查 [英] Use of null check in event handler

查看:96
本文介绍了在事件处理程序使用null检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当检查,如果事件处理程序为null,则这在每个线程的基础上完成的?

When checking if an event handler is null, is this done on a per-thread basis?

确保有人听事件是这样完成的:

Ensuring someone is listening to the event is done like this:

EventSeven += new DivBySevenHandler(dbsl.ShowOnScreen);

如果我加code以下上面,我检查空这个模式,那么为什么我需要一个空检查(的 /csevents01.aspx\">$c$c拍摄)。我缺少什么?

If I add code following this pattern above where I check for null, then why would I need a null check (code taken from this site). What am I missing?

此外,什么是事件和GC规则?

Also, what's the rule with events and GC?

推荐答案

这真的不清楚你的意思我很害怕,但如果有委托为无效的可能性,你需要单独检查每个线程上。通常情况下,你会怎么做:

It's really not clear what you mean I'm afraid, but if there's the possibility of the delegate being null, you need to check that separately on each thread. Typically you'd do:

public void OnSeven()
{
    DivBySevenHandler handler = EventSeven;
    if (handler != null)
    {
        handler(...);
    }
}

这确保了即使 EventSeven 过程中的变化 OnSeven(),你不会得到一个的NullReferenceException

This ensures that even if EventSeven changes during the course of OnSeven() you won't get a NullReferenceException.

但你是正确的,你不需要空检查,如果你确实有一个订阅的处理程序。这很容易在C#2来完成一个无操作处理程序:

But you're right that you don't need the null check if you've definitely got a subscribed handler. This can easily be done in C# 2 with a "no-op" handler:

public event DivBySevenHandler EventSeven = delegate {};

在另一方面,你的可能的需要某种锁定只是为了确保你有最新的设置处理程序,如果你可能会得到不同的线程订阅。我在我的线程教程一个例如,它可以帮助 - 但通常我建议尽量避免需要它。

On the other hand, you might want some sort of locking just to make sure that you've got the "latest" set of handlers, if you might get subscriptions from various threads. I have an example in my threading tutorial which can help - although usually I'd recommend trying to avoid requiring it.

在垃圾收集,该事件的方面的发布的结束与参照事件的订户的(即,处理程序的目标)。如果发布是指活长于订户,这是唯一的一个问题。

In terms of garbage collection, the event publisher ends up with a reference to the event subscriber (i.e. the target of the handler). This is only a problem if the publisher is meant to live longer than the subscriber.

这篇关于在事件处理程序使用null检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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