开发者

how to clear event handles in c#

I'm using global variable named "client"

For example

client.getPagesCompleted += (s, ee) =>
{
    pages = ee.Result;
    BuildPages(tvPages.Items, 0);
    wait.Close();
};
client.getPagesAsync(cat.MainCategor开发者_如何学GoyID);

I need to clear handlers for getPagesCompleted and set another handler.

How to easy clear handles?

I know client.getPagesCompleted-=new EventHandler(...). But it is very difficult. I need easy way. I'm using client.getPagesCompleted=null but error shown. "only use += / -+"


The only way to remove an event handler is to use the -= construct with the same handler as you added via +=.

If you need to add and remove the handler then you need to code it in a named method rather using an anonymous method/delegate.


You don't have to put your event handler in a separate method; you can still use your lambda function, but you need to assign it to a delegate variable. Something like:

MyEventHandler handler = (s, ee) => 
{ 
    pages = ee.Result; 
    BuildPages(tvPages.Items, 0); 
    wait.Close(); 
}; 

client.getPagesCompleted += handler; // Add event handler
// ...
client.getPagesCompleted -= handler; // Remove event handler


Save the event object to a variable, and use -= to unsubscribe.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜