繁体   English   中英

第一个实验调用异步方法-我需要所有这些代码吗?

[英]First experiment calling asynch method - Do I need ALL this code?

从未尝试使用Windows Form进行异步调用。 我不能使用新的aynch/await因为我不拥有最新的Visual Studio / .NET。 我需要的是“执行一个请求很长时间的操作(填充一个IList)”,完成后,将该列表的结果写在TextBox上。

在Internet上搜索时,我发现此示例似乎可行,但我认为TOO符合要求(也许有些快速简便):

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行代码来实现这种简单的操作吗? 或者我可以删除一些东西? 完成后,我只需要一个简单的asynch call-> callback。

没有锁,根本没有并发...

您可以将TPL与C#4.0结合使用,如下所示:

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线程中运行UpdateUIWithResultsUpdateUIWithResults其传递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...";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM