如何知道异步方法是否正在运行

时间:2013-08-17 16:46:15

标签: c# multithreading task-parallel-library async-await

我有一个点击事件的按钮,从服务器获取数据并在网格上显示。

代码如下:

private void btnSearch_Click(object sender, EventArgs e)
{
    // Here I should do something in order to know if the async ProcessSearch method is busy..
    // if not busy then I will execute it if not then I will return.
    // shows loading animation
    ShowPleaseWait(Translate("Searching data. Please wait..."));
    ProcessSearch();
}

private async void ProcessSearch()
{
    Data.SeekWCF seekWcf = new Data.SeekWCF();
    _ds = await seekWcf.SearchInvoiceAdminAsync(new Guid(cboEmployer.Value.ToString()), new Guid(cboGroup.Value.ToString()), txtSearchInvoiceNumber.Text, chkSearchLike.Checked, txtSearchFolio.Text, Convert.ToInt32(txtYear.Value));
    seekWcf.Dispose();

    if (_ds != null)
    {
        SetupInvoiceGrid();
    }
    // hides the loading animation
    HidePleaseWait();
}

我怎么知道异步方法ProcessSearch是忙还是正在运行所以我可以阻止用户再次单击按钮时再次执行该方法。

1 个答案:

答案 0 :(得分:4)

你可以设置一个布尔值:

private bool isSearching = false;

private void btnSearch_Click(object sender, EventArgs e)
{
    if (isSearching)
        return;
    // shows loading animation
    ShowPleaseWait(Translate("Searching data. Please wait..."));
    ProcessSearch();
}

private async void ProcessSearch()
{
    isSearching = true;

    // do other stuff

    isSearching = false;
}

如果您关注并发性,可以添加lock

private bool isSearching = false;
private object lockObj = new object();

private void btnSearch_Click(object sender, EventArgs e)
{
    lock (lockObj)
    {
        if (isSearching)
            return;
        else
            isSearching = true;
    }
    // shows loading animation
    ShowPleaseWait(Translate("Searching data. Please wait..."));
    ProcessSearch();
}

private async void ProcessSearch()
{
    // do other stuff

    isSearching = false;
}