开发者

Call instance method from static time callback

I have a timer within a class, and when this timer fires I want to call an instance method of this class. How do I access this from the static timer callback method?

private void ClassInstanceMethod()
{
}

public static void TimerFired(object source, ElapsedEventArgs e)
{
    // Want to call ClassInstanceMethod() here
}

private void startTimer()
{
    timer = new Timer();
    timer.Interval = 1000;
    timer.Elapsed += new ElapsedEventHandl开发者_如何学Goer(TimerFired);
    timer.AutoReset = false;
    timer.Enabled = true;
}

Solved

I had the misconception that TimerFired had to be static - which it does not.


You can't. The source parameter is the Timer object, and the ElapsedEventArgs object doesn't contain any reference to the instance of your class. As was discussed in the comments, you can make the TimerFired method non-static (i.e., instance), and from there you'll be able to safely call ClassInstanceMethod and other instance methods from the class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜