I need to execute many methods at the same time and the result of all, concatenate them in a single list. In the following example, I wait 3 seconds for each method, but in one of them I added a sleep (10 seconds) to check the result and it is not the expected one. The method never cancels and waits for those 10 seconds. What is the problem? Thank you!
var result = await Task.Run(() => Load<MyCustomClass>(OneMethod(), OtherMethod())); private List<T> OneMethod() { return new List<T>(); } private List<T> OtherMethod() { Thread.Sleep(10000); return new List<T>(); } private async Task<List<T>> Load<T>(params List<T>[] taskList) { try { return (await Task.WhenAll(taskList.Select(x => Task.Run(() => x, new CancellationTokenSource(3000).Token)))).SelectMany(x => x).ToList(); } catch (Exception currentException) { //BLA BLA BLA } return new List<T>(); }
Thread.Sleep(), when you should be using the Task based equivalent,Task.Delay()await Task.Run(() => Load..and writeawait Load..Task.Run?