Running multiple C# Task Async

前端 未结 3 1412
暗喜
暗喜 2021-01-04 19:48

Hi normally I would do this with a Background Worker, but I would like to do it with C# Task instead, just to understand Task better.

The thing is that I have a clas

相关标签:
3条回答
  • 2021-01-04 20:24
    Task<int>.Factory.StartNew(() => GenerateResult2()).ContinueWith(() => GenerateResult());
    
    0 讨论(0)
  • 2021-01-04 20:26

    I checked this: Task Parallelism (Task Parallel Library) and it it states that when using System.Threading.Tasks.Task<TResult> the Tasks run asynchronously and may complete in any order. If Result is accessed before the computation completes, the property will block the thread until the value is available.

    I think that means if you are accessing .Result before it has a value, as you are doing in your sample code, you will have to wait for it to complete first.

    It does make sense as the Result property would not be populated until the Task is completed.

    0 讨论(0)
  • 2021-01-04 20:39

    When you get the Result property, you are effectively waiting for the task to complete. It will execute on a background thread but you are waiting in your main thread for the completion before you start the next thread.

    See the MSDN doc for details.

    You should be able to just assign your properties from the background thread:

    Task<int>.Factory.StartNew(() => Number1 = GenerateResult());
    

    WPF databinding will take care of marshalling the PropertyChanged event to the correct dispatcher thread.

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