TutuGeorge
TutuGeorge

Reputation: 2022

How to handle mutiple async methods from running?

How can i know if an async(awaitable) operation is already running and waiting for completion in the application. I have two buttons in a view each binded to two differrent async methods. If button1 is clicked and the async is started and waiting for its result. And at that time if the button2 is clicked. I need to show a message that an already running async methos is there and stop the second async method from executing. How can i achieve this?

Upvotes: 2

Views: 116

Answers (3)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You can store the executed Task inside your form and look up its Status property:

public class Form1
{
    private Task fooTask = Task.FromResult(0);

    public Task FooAsync()
    {
        return Task.FromResult(0);
    }

    public async void MyEventHandler(object sender, EventArgs e)
    {
        if (fooTask.Status == TaskStatus.Running)
        {
            // If we got here, the task is currently running. Notify someone
            return;
        }

        // If we're here, the task isn't running.
    }
}

Note this doesn't take care of situations where your task might be in a Faulted or Canceled state, which you may want to handle as well.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

Store the task and check for IsCompleted Property.

private Task pendingTask = Task.FromResult(0);

private async void Button1Click()
{
    if (!pendingTask.IsCompleted)
    {
        //Notify the user
        return;
    }

    pendingTask = DoSomethingAsync();
    await pendingTask;
    ...
}

private async  void Button2Click()
{
    if (!pendingTask.IsCompleted)
    {
        //Notify the user
        return;
    }

    pendingTask = DoSomethingElseAsync();
    await pendingTask;
    ...
}

As noted by @Peter Ritchie in comments, better idea is to disable the other button when asynchronous operation is pending. You may consider using it.

Upvotes: 7

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943

Task class has a Status property which can be used to evaluate if an asynchronous operation is running or it has completed or even if it's in faulted state.

Upvotes: 2

Related Questions