[英]How do I use an asynchronous delegate?
我有一個 C# windows 窗體應用程序。 我的一個按鈕有這個事件:
private void btnNToOne_Click(object sender, EventArgs e)
{
int value = (int)numUpToThis.Value;
textResult.Text = Program.asyncCall(value, 2).ToString();
}
它調用的方法是這個:
public delegate int DelegateWithParameters(int numar, int tipAlgoritm);
public static int asyncCall(int numar, int tipAlgoritm)
{
DelegateWithParameters delFoo = new DelegateWithParameters(calcPrim);
IAsyncResult tag = delFoo.BeginInvoke(numar, tipAlgoritm, null, null);
while (tag.IsCompleted == false)
{
Thread.Sleep(250);
}
int intResult = delFoo.EndInvoke(tag);
return intResult;
}
問題是它一直阻塞我的用戶界面,所以我顯然做錯了什么。 我應該如何使用異步委托? 有小費嗎?
下面是這個特殊情況的一個快速示例,當您需要這樣的東西時,您通常可以使用它。
首先,不能把整個異步邏輯封裝在方法里面,因為結果不能用return語句提供,所以只提供同步方法
static class MyUtils
{
public static int CalcPrim(int numar, int tipAlgoritm)
{
// ...
}
}
然后在您的表單中使用以下內容
private void btnNToOne_Click(object sender, EventArgs e)
{
int value = (int)numUpToThis.Value;
Action<int> processResult = result =>
{
// Do whatever you like with the result
textResult.Text = result.ToString();
}
Func<int, int, int> asyncCall = MyUtils.CalcPrim;
asyncCall.BeginInvoke(value, 2, ar =>
{
// This is the callback called when the async call completed
// First take the result
int result = asyncCall.EndInvoke(ar);
// Note that the callback most probably will called on a non UI thread,
// so make sure to process it on the UI thread
if (InvokeRequired)
Invoke(processResult, result);
else
processResult(result);
}, null);
}
最后,只是為了比較,等價的async/await
代碼
private async void btnNToOne_Click(object sender, EventArgs e)
{
int value = (int)numUpToThis.Value;
int result = await Task.Run(() => MyUtils.CalcPrim(value, 2));
textResult.Text = result.ToString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.