Asynchronous method C# WhenAll issue

Recently I ran into a problem with calling 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 method InitClassAObject() never returns. Breakpoint at "return never" hit.

Question 2: If I call multiple async method and they update different properties of the object ClassA. Is it safe to do so?

I've searched around for a solution but still not found. Thank you.

Upvotes: 3

Views: 101

Answers (2)

Denis Krasakov
Denis Krasakov

Reputation: 1578

About Question 2: It's safe to update different properties. But you should keep in mind that if you read SomeProperty in Task1 and modify it in Task2 result will be unpredictable (Task1 may read before or after Task2 write)

Upvotes: 2

Numan KIZILIRMAK
Numan KIZILIRMAK

Reputation: 565

Functions are using the same source(object) because of that can cause deadlock? can you please not use same object and see result?

Upvotes: 2

Related Questions