第一个实验调用asynch方法-我需要所有这些代码
本文关键字:所有这些 代码 实验 调用 asynch 方法 第一个 | 更新日期: 2023-09-27 18:09:35
从未尝试使用Windows窗体进行异步调用。我不能使用新的aynch/await
,因为我没有最近的Visual Studio/. net。我需要的是"执行一个请求很长时间的操作(填充一个列表)",当它完成时,在TextBox上写入该列表的结果。
在网上搜索,我发现这个例子,似乎工作,但太符合我的意见(也许有一些快速和简单的):
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行代码来做这么简单的操作吗?或者我可以去掉一些东西?我只需要一个简单的异步调用->完成后回调。
您可以像这样使用c# 4.0的TPL:
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => DoWork())
.ContinueWith(t => UpdateUIWithResults(t.Result)
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext());
}
这将在线程池线程中启动DoWork
,允许它在UI线程外进行处理,然后在UI线程中运行UpdateUIWithResults
,将DoWork
的结果传递给它。
您可以使用Task.Factory.StartNew
将工作推入线程池。Task.ContinueWith
会给你一个"完成回调"。
private void button1_Click(object sender, EventArgs e)
{
var ui = TaskScheduler.FromCurrentSynchronizationContext();
Task<List<T>> task = Task.Factory.StartNew(() => MyTaskWorker());
task.ContinueWith(t => OnMyTaskCompleted(t), ui);
}
private List<T> MyTaskWorker()
{
// here I populate the list. I emulate this with a sleep of 3 seconds
Thread.Sleep(3000);
return ...;
}
protected virtual void OnMyTaskCompleted(Task t)
{
// here I'll populate the textbox with t.Result
textBox1.Text = "... content of the Iteration on the List...";
}