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.
source
share