将静态方法与事件处理程序一起使用

时间:2013-02-04 18:46:35

标签: c# asynchronous

我继承了一个拥有大量静态方法的C#(.NET 2.0)应用程序。我需要将其中一种方法转换为基于异步事件的方法。当方法完成后,我想触发一个事件处理程序。我的问题是,我可以从静态方法中触发事件处理程序吗?如果是这样,怎么样?

当我谷歌时,我只找到IAsyncResult示例。但是,我希望能够执行以下操作:

EventHandler myEvent_Completed;
public void DoStuffAsync()
{
  // Asynchrously do stuff that may take a while
  if (myEvent_Completed != null)
    myEvent_Completed(this, EventArgs.Empty);
} 

谢谢!

3 个答案:

答案 0 :(得分:4)

过程完全相同,唯一的区别是没有真正的this参考。

static EventHandler myEvent_Completed;

public void DoStuffAsync()
{
    FireEvent();
} 

private static void FireEvent()
{
    EventHandler handler = myEvent_Completed;

    if (handler != null)
        handler(null, EventArgs.Empty);
}

答案 1 :(得分:3)

如果DoStuffAsync是静态的(它不在您的代码中),则事件myEvent_Completed也需要变为静态:

static EventHandler myEvent_Completed; // Event handler for all instances

public static void DoStuffAsync()
{
  // Asynchrously do stuff that may take a while
  if (myEvent_Completed != null)
    myEvent_Completed(null, EventArgs.Empty);
} 

否则,DoStuffAsync需要使用您的类的实例来触发事件:

EventHandler myEvent_Completed; // Note: Can still be private

public static void DoStuffAsync(YourClass instance)
{
   // Asynchrously do stuff that may take a while
   if(instance.myEvent_Completed != null)
      instance.myEvent_Completed(instance, EventArgs.Empty);
}

如果你需要不同的类实例来为这个事件提供不同的事件处理程序,你需要使用后一个路由并传入一个实例。

除此之外,从静态方法触发事件绝对没有错。

答案 2 :(得分:0)

如果在您正在操作的类型中声明event,您可以传入一个实例(如果它是Singleton则恢复它)并从那里访问event对象。所以,例如:

EventHandler myEvent_Completed;
public void DoStuffAsync(MyClass o)
{
    // Asynchrously do stuff that may take a while
    if (o.myEvent_Completed != null)
        o.myEvent_Completed(this, EventArgs.Empty);
} 

如果是单身人士,你可以这样做:

EventHandler myEvent_Completed;
public void DoStuffAsync(MyClass o)
{
    // Asynchrously do stuff that may take a while
    if (Instance.myEvent_Completed != null)
        Instance.myEvent_Completed(this, EventArgs.Empty);
} 

其中Instance是Singleton访问者。

相关问题