【发布时间】:2026-02-04 04:20:03
【问题描述】:
我有一个按钮,点击事件会从服务器获取数据并将其显示在网格上。
代码如下:
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 是忙还是正在运行,这样我就可以防止用户在再次单击按钮时再次执行该方法。
【问题讨论】:
-
顺便说一句,你应该只在顶层使用
async void。也就是说,ProcessSearch()应该是async Task方法,btnSearch_Click应该是async void方法,awaits 是ProcessSearch()的结果。
标签: c# multithreading task-parallel-library async-await