2013-08-17 103 views
0

我有一個按鈕,點擊事件發送並從服務器獲取數據並將其顯示在網格上。如何知道異步方法是否正在運行

的代碼如下圖所示:

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忙或運行,所以我可以阻止用戶再次點擊該按鈕時,再次執行方法。

+0

BTW,你應該只在使用'異步void'的頂層。也就是說,'ProcessSearch()'應該是一個'async Task'方法,'btnSearch_Click'應該是一個'async void'方法,它等待'ProcessSearch()'的結果。 – svick

回答

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; 
} 
+1

在異步運算符中是否沒有內置「IsBusy」屬性?像BackgroundWorkers一樣? – VAAA

+1

從技術上講,這段代碼很容易出現競爭狀況。雖然不太可能發生,但您應該使用鎖來保護自己。 – BrokenGlass

+0

@VAAA有'Task.IsCompleted',但要使用它你必須使它'私人異步任務ProcessSearch()'並將該任務存儲在一個字段中;海事組織,只是存儲一個布爾值更簡單。 –

相關問題