Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 277
Đức Toàn Dương Avatar asked Jul 12 '26 18:07

Đức Toàn Dương


2 Answers

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)

like image 176
Denis Krasakov Avatar answered Jul 14 '26 08:07

Denis Krasakov


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

like image 27
Numan KIZILIRMAK Avatar answered Jul 14 '26 08:07

Numan KIZILIRMAK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!