从未尝试过使用 Windows 窗体进行异步调用。我不能使用新的aynch/await
,因为我没有最近的 Visual Studio/.NET。我需要的是“执行请求长时间的操作(填充 IList)”,当它完成后,在 TextBox 上写入该列表的结果。
在 Internet 上搜索,我发现这个示例似乎可行,但在我看来也符合要求(也许有些东西既快速又简单):
private void button1_Click(object sender, EventArgs e)
{
MyTaskAsync();
}
private void MyTaskWorker()
{
// here I populate the list. I emulate this with a sleep of 3 seconds
Thread.Sleep(3000);
}
private delegate void MyTaskWorkerDelegate();
public void MyTaskAsync()
{
MyTaskWorkerDelegate worker = new MyTaskWorkerDelegate(MyTaskWorker);
AsyncCallback completedCallback = new AsyncCallback(MyTaskCompletedCallback);
AsyncOperation async = AsyncOperationManager.CreateOperation(null);
worker.BeginInvoke(completedCallback, async);
}
private void MyTaskCompletedCallback(IAsyncResult ar)
{
MyTaskWorkerDelegate worker = (MyTaskWorkerDelegate)((AsyncResult)ar).AsyncDelegate;
AsyncOperation async = (AsyncOperation)ar.AsyncState;
worker.EndInvoke(ar);
AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null, false, null);
async.PostOperationCompleted(delegate(object e) { OnMyTaskCompleted((AsyncCompletedEventArgs)e); }, completedArgs);
}
public event AsyncCompletedEventHandler MyTaskCompleted;
protected virtual void OnMyTaskCompleted(AsyncCompletedEventArgs e)
{
if (MyTaskCompleted != null)
MyTaskCompleted(this, e);
// here I'll populate the textbox
textBox1.Text = "... content of the Iteration on the List...";
}
对于这个简单的操作,我真的需要 50 行代码吗?或者我可以删除一些东西?我只需要一个简单的异步调用->完成后的回调。
没有锁,根本没有并发......