We run 2 threads in parallel, they perform some kind of long-term work. We know that then A will execute faster than flow B. How, after completion, does A transfer its result to flow B?

It comes to mind a head-on solution: write the results of the work of the first thread into a static variable and read it in the second thread. But it seems to me there are better ways. Maybe you know how to do this?

  • Static is a bust. It is better to write not to a static variable, but to an instance common to both threads. Create a class with a variable and hand an instance of the class to both threads. - vitidev
  • @vitidev why is the instance better than static? - Pupkin
  • one
    Because only the necessary streams are visible and do not need to be cleaned after the end of the streams. Statics only for ever- living things - vitidev
  • You gave an example of a task, but there is probably a real use of it. Most likely, this is not just a variable for you, but a collection of some kind of data calculated in one of the parallel streams, so there are tools like Parallel.ForEach for exactly parallel execution of the mass of streams, and for storing the results of such calculations - ConcurrentBag ( habrahabr.ru/ post / 241706 ). So far you are considering a simple task, but in the end you will have to deal with more massive calculations. Learn, try, improve! =) - gromanev

2 answers 2

The correct option is not to work with a low-level abstraction flow at all. To return values, you have Task<T> , and use it.

For example:

 Task<int> Compute() { return Task.Run(() => { int result; // длинные сложные вычисления return result; }; } 

Now this result can be used:

 Task<int> computeTask = Compute(); // проверить, завершились ли вычисления if (computeTask.IsCompleted) // ... // дождаться окончания работы и получить результат int result = await computeTask; 
      string s = ""; Task<int> A = new Task<int>(() => { Thread.Sleep(500); //..... s = s + "Return 77 from A\n"; return 77; }); Task B= new Task(async () => { Thread.Sleep(2000); //..... var x = await A; s = s + string.Format("B got {0} from A",x); }); A.Start(); B.Start(); B.Wait(); Console.WriteLine(s);