C # Asynchronous Method WhenAll issue

I recently ran into the problem of calling an asynchronous method. Here is the code:

ClassA storage = new ClassA();// this is member of the class

async Task<ClassA> InitClassAObject(){ // async method of the class


    List<Task> taskList = new List<Task>(); // create list task
        taskList.Add(Func1());
        taskList.Add(Func2());
        taskList.Add(Func3());            

        await Task.WhenAll(taskList.ToArray()); // wait for all task done

        return storage; // <--- this line never be hit
 }

 async Task Func1(){
        await Task.Run(() =>{
          //update property A of storage
          //example storage.A = GetDataFromSomeWhere();
   });
 }

 async Task Func2(){
        await Task.Run(() =>{
          //update property B of storage
          //example storage.B = GetDataFromSomeWhereElse();
   });
 }
 ...

Question 1: The InitClassAObject () method never returns. The "never return" breakpoint did not hit.

Question 2: If I call several async methods and they update different properties of the ClassA object. Is it safe to do this?

I searched for a solution, but still could not find. Thank.

+4
source share
2 answers

About Question 2: Safely Updating Various Properties. But you should keep in mind that if you read SomeProperty in Task1 and change it in Task2, the result will be unpredictable (Task1 may read before or after writing Task2)

+2

(), ? ?

+3

Source: https://habr.com/ru/post/1673389/


All Articles