Running multiple C # Task Async tasks

Hi, I usually did this with a background worker, but I would like to do this using C # Task instead, in order to better understand the task.

The fact is that I have a class with the following properties

private int _number1; public int Number1 { get { return _number1; } set { _number1 = value; OnPropertyChanged("Number1");} } private int _number2; public int Number2 { get { return _number2; } set { _number2 = value; OnPropertyChanged("Number2");} } 

Please note that I am using INotifyPropertyChanged.

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

GenerateResult and GenerateResult2 are just dumme methods that sleep and then return a number.

How can I make this Async work? Because right now, GenerateResult2 () is first called when GenerateResult () is complete.

I need him to be able to run Async, since I have no idea when each task will end or even if it will end.

+9
multithreading c #
Sep 21 '10 at 8:28
source share
3 answers

When you get the Result property, you really expect the task to complete. It will execute in the background thread, but you wait in your main thread for completion before starting the next thread.

See the MSDN document for more details.

You can simply assign your properties from the background thread:

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

WPF data binding will take care of sorting the PropertyChanged event in the correct dispatcher thread.

+13
Sep 21 '10 at 8:31
source share

I checked this: Parallelism task (parallel task library) and it states that when using System.Threading.Tasks.Task<TResult> Tasks start asynchronously and can end in any order. If Result is available before the computation is completed, the property will block the thread until the value is available.

I think this means that if you access .Result before it matters, as you do in your code example, you will have to wait for it to complete.

This makes sense because the Result property will not be populated until the task completes.

+3
Sep 21 '10 at 8:43
source share
 Task<int>.Factory.StartNew(() => GenerateResult2()).ContinueWith(() => GenerateResult()); 
-four
Sep 21 '10 at 8:31
source share



All Articles