简体   繁体   中英

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?

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.

Task类具有Status属性,可用于评估异步操作是否正在运行或已完成,或者即使它处于故障状态。

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.

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