Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Await to Keep Event Firing

I have a question about async\await in a C# .NET app. I'm actually trying to solve this problem in a Kinect based application but to help me illustrate, I've crafted this analogous example:

Imagine that we have a Timer, called timer1 which has a Timer1_Tick event set up. Now, the only action I take on that event is to update the UI with the current date time.

 private void Timer1_Tick(object sender, EventArgs e)
    {
        txtTimerValue.Text = DateTime.Now.ToString("hh:mm:ss.FFF", CultureInfo.InvariantCulture);
    }

This is simple enough, my UI updates every few hundredths of seconds and I can happily watch time go by.

Now imagine that I also want to also calculate the first 500 prime numbers in the same method like so:

 private void Timer1_Tick(object sender, EventArgs e)
    {
        txtTimerValue.Text = DateTime.Now.ToString("hh:mm:ss.FFF", CultureInfo.InvariantCulture);
        List<int> primeNumbersList = WorkOutFirstNPrimeNumbers(500);
        PrintPrimeNumbersToScreen(primeNumbersList);
    }

    private List<int> WorkOutFirstNPrimeNumbers(int n)
    {
        List<int> primeNumbersList = new List<int>();
        txtPrimeAnswers.Clear();
        int counter = 1;
        while (primeNumbersList.Count < n)
        {
            if (DetermineIfPrime(counter))
            {
                primeNumbersList.Add(counter);

            }
            counter++;
        }

        return primeNumbersList;
    }

    private bool DetermineIfPrime(int n)
    {
        for (int i = 2; i < n; i++)
        {
            if (n % i == 0)
            {
                return false;
            }
        }
        return true;
    }
    private void PrintPrimeNumbersToScreen(List<int> primeNumbersList)
    {
        foreach (int primeNumber in primeNumbersList)
        {
            txtPrimeAnswers.Text += String.Format("The value {0} is prime \r\n", primeNumber);
        }
    }

This is when I experience the problem. The intensive method that calculates the prime numbers blocks the event handler from being run - hence my timer text box now only updates every 30 seconds or so.

My question is, how can I resolve this while observing the following rules:

  • I need my UI timer textbox to be as smooth as it was before, probably by pushing the intensive prime number calculation to a different thread. I guess, this would enable the event handler to run as frequently as before because the blocking statement is no longer there.
  • Each time the prime number calculation function finishes, it's result to be written to the screen (using my PrintPrimeNumbersToScreen() function) and it should be immediately started again, just in case those prime numbers change of course.

I have tried to do some things with async/await and making my prime number calculation function return a Task> but haven't managed to resolve my problem. The await call in the Timer1_Tick event still seems to block, preventing further execution of the handler.

Any help would be gladly appreciated - I'm very good at accepting correct answers :)

Update: I am very grateful to @sstan who was able to provide a neat solution to this problem. However, I'm having trouble applying this to my real Kinect-based situation. As I am a little concerned about making this question too specific, I have posted the follow up as a new question here: Kinect Frame Arrived Asynchronous

like image 976
Benjamin Biggs Avatar asked Aug 16 '15 13:08

Benjamin Biggs


2 Answers

May not be the best solution, but it will work. You can create 2 separate timers. Your first timer's Tick event handler only needs to deal with your txtTimerValue textbox. It can remain the way you had it originally:

private void Timer1_Tick(object sender, EventArgs e)
{
    txtTimerValue.Text = DateTime.Now.ToString("hh:mm:ss.FFF", CultureInfo.InvariantCulture);
}

For your 2nd timer's Tick event handler, define the Tick event handler like this:

private async void Timer2_Tick(object sender, EventArgs e)
{
    timer2.Stop(); // this is needed so the timer stops raising Tick events while this one is being awaited.

    txtPrimeAnswers.Text = await Task.Run(() => {
        List<int> primeNumbersList = WorkOutFirstNPrimeNumbers(500);
        return ConvertPrimeNumbersToString(primeNumbersList);
    });

    timer2.Start(); // ok, now we can keep ticking.
}

private string ConvertPrimeNumbersToString(List<int> primeNumbersList)
{
    var primeNumberString = new StringBuilder();
    foreach (int primeNumber in primeNumbersList)
    {
        primeNumberString.AppendFormat("The value {0} is prime \r\n", primeNumber);
    }
    return primeNumberString.ToString();
}

// the rest of your methods stay the same...

You'll notice that I changed your PrintPrimeNumbersToScreen() method to ConvertPrimeNumbersToString() (the rest remains the same). The reason for the change is that you really want to minimize the amount of work being done on the UI thread. So best to prepare the string from the background thread, and then just do a simple assignment to the txtPrimeAnswers textbox on the UI thread.

EDIT: Another alternative that can be used with a single timer

Here is another idea, but with a single timer. The idea here is that your Tick even handler will keep executing regularly and update your timer value textbox every time. But, if the prime number calculation is already happening in the background, the event handler will just skip that part. Otherwise, it will start the prime number calculation and will update the textbox when it's done.

// global variable that is only read/written from UI thread, so no locking is necessary.
private bool isCalculatingPrimeNumbers = false; 

private async void Timer1_Tick(object sender, EventArgs e)
{
    txtTimerValue.Text = DateTime.Now.ToString("hh:mm:ss.FFF", CultureInfo.InvariantCulture);

    if (!this.isCalculatingPrimeNumbers)
    {
        this.isCalculatingPrimeNumbers = true;
        try
        {
            txtPrimeAnswers.Text = await Task.Run(() => {
                List<int> primeNumbersList = WorkOutFirstNPrimeNumbers(500);
                return ConvertPrimeNumbersToString(primeNumbersList);
            });
        }
        finally
        {
            this.isCalculatingPrimeNumbers = false;
        }
    }
}

private string ConvertPrimeNumbersToString(List<int> primeNumbersList)
{
    var primeNumberString = new StringBuilder();
    foreach (int primeNumber in primeNumbersList)
    {
        primeNumberString.AppendFormat("The value {0} is prime \r\n", primeNumber);
    }
    return primeNumberString.ToString();
}

// the rest of your methods stay the same...
like image 96
sstan Avatar answered Oct 16 '22 17:10

sstan


You should avoid using async/await (despite how good they are) because Microsoft's Reactive Framework (Rx) - NuGet either "Rx-WinForms" or "Rx-WPF" - is a far better approach.

This is the code you would need for a Windows Forms solution:

private void Form1_Load(object sender, EventArgs e)
{
    Observable
        .Interval(TimeSpan.FromSeconds(0.2))
        .Select(x => DateTime.Now.ToString("hh:mm:ss.FFF", CultureInfo.InvariantCulture))
        .ObserveOn(this)
        .Subscribe(x => txtTimerValue.Text = x);

    txtPrimeAnswers.Text = "";

    Observable
        .Interval(TimeSpan.FromSeconds(0.2))
        .Select(n => (int)n + 1)
        .Where(n => DetermineIfPrime(n))
        .Select(n => String.Format("The value {0} is prime\r\n", n))
        .Take(500)
        .ObserveOn(this)
        .Subscribe(x => txtPrimeAnswers.Text += x);
}

That's it. Very simple. It all happens on background threads before being marshalled back to the UI.

The above should be fairly self explanatory, but yell out if you need any further explanation.

like image 2
Enigmativity Avatar answered Oct 16 '22 17:10

Enigmativity