简体   繁体   中英

checking completion of void async method

I have an event handler (from a timer) that redraws every x milliseconds.

Even though it is (apparently) not best practice to use async void methods, this is apparently not true for event handlers since the developer doesn't call them from other methods.

My problem is I've noticed that when the processor has a heavy workload (background tasks, etc), overlapping calls to redraw are made.

I've been able to get around this by setting a flag (bool variable) to indicate the drawing is complete (and not calling my draw method unless this flag is true), but I've heard Windows store apps can be rejected for polling on async activity.

private void _timer_Tick(object sender, object e)
{
    if (drawingFinished == true)
    {
        drawingFinished = false;

        // drawingFinished set to true at the end of this method
        DrawVideoFrame();    
    }
}

Also, you can't add locks to async methods.

What is best practice here? How should I go about this?

Have you seen this article http://msdn.microsoft.com/en-us/magazine/jj991977.aspx from the March 2013 issue of MSDN Magazine? The first section of the article discusses async event handlers to some extent. It isn't a direct solution to your problem, but it may give you a hint.

My method looks more like this now:

private void _timer_Tick(object sender, object e)
{
    _timer.Stop();

    DrawVideoFrame();    // calls timer.Start() as one the last line
}

I see pro's and con's to this solution:

Pros: (1) It feels less like a kludge (sp?). (2) Microsoft has, uh, less grounds to reject my app because I'm not checking a completion condition. (3) My drawing method is definitely not getting interrupted now. (4) Despite my best efforts it is working as desired ;)

Cons: I'm not really scheduling when the frames are drawn anymore. So instead of setting the timeout for 1000 ms and thinking it will get called (at most) 1 Hz, high-end machines will see a faster number of frames (since the only fixed length of time is between calls to DrawVideoFrame()). I guess that is the nature of surfing the async wave, so to speak.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM