How to ContinueWith another function with result from previous task when using Tasks?

后端 未结 1 928
情深已故
情深已故 2020-12-24 02:12

I have WCF connector that should get some small amount of data for me, usually it takes up to 20 seconds to get this data for each item ( which is fine ). I want to use Task

1条回答
  •  生来不讨喜
    2020-12-24 02:33

    In the example below previousTask references the previous task, use the Result property to get the return value from it.

    Task task = Task.Factory.StartNew(() =>
    {
       // Background work
       return ipVersionCounters;
    }).ContinueWith((previousTask) => 
    {
       var ipVersionCounters = previousTask.Result;
    });
    

    Update

    If you want the continuewith to execute on the UI thread use (If you are starting on the UI thread) ...

    Task.Factory.StartNew(() =>
    {
      // Background work
    }).ContinueWith((previousTask) => {
      // Update UI thread
    }, TaskScheduler.FromCurrentSynchronizationContext());
    

    (which was taken from this answer for more info)

    0 讨论(0)
提交回复
热议问题