簡體   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