开发者

Can any one tell me if the example I have mentioned is an example of a callback mechanism

class B
{
     public delegate void CallBack();
     public event CallBacl cllBack;

     void Publish()
     {
       cllBack();
     }
}

class A
{
     B b = new B();
     b.cllBack += new CallBack(test_this)
开发者_如何学编程
     public void test_this()
     {

     }
}
  1. Does the above example represent a way of implementing the call back mechanism in .net?
  2. Or else do I need to use BeginInvoke and endInvoke for the call back mechanism?


  1. Yes, this is one method. Anyway I'll check this: if (cllBack != null) cllBack();
  2. BeginInvoke (look here) is used for asyncronous operations; the method you're using is the syncronous one.


There are many ways of implementing a callback mechanism, and using delegates is indeed one of them.

See this for info on begininvoke etc. also see that for an alternative.


one caveat that it cost me some pain:

b.cllBack += new CallBack(test_this)

of course adds a reference to b in a, so even if you do not use b anymore in any other place, b is still referenced and will not be garbage collected.

what i think is a neater approach:

class A
{
    private delegate B.CallBack myCallBack;
    private B b = new B();

    public A
    {
       myCallBack = new B.CallBack( test_this );
       b.cllBack += myCallBack;
    }


   public void Close()
   {
     c.cllBack -= myCallBack;
   }
}

In short you register when you need the callback, and unregister when you no longer need the callback.

hth

Mario

PS: be careful, your b is local to the ctor

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜