[英]How to know if an async method is running
我有一个按钮,单击事件会发生,并从服务器获取数据并将其显示在网格上。
代码如下:
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是忙还是正在运行,所以我可以防止用户在再次单击按钮时再次执行该方法。
您可以设置一个布尔值:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.