Return null from task

var hs = new HashSet<int>(); foreach(var item in mainclass) { Task<List<Class1>> cl1Task = Task.Factory.StartNew<List<Class1>>(() => { if (!hs_VersiodIDs.Contains(item.VersionID)) { return new List<Class1>(.....); } else { return null; } }); Task.WaitAll(cl1Task ); } 

He does not wait for the completion of the task. The problem is returning null, so how can I return an empty task?

+4
source share
1 answer

Your code does not make sense for two reasons:

  • Running a task that does not contain long code is useless. You will not benefit from this.
  • Waiting for a task to complete immediately after it starts completely negates the effect of the task: you still block the main thread.

Change your code to this if the code in the task is really so simple:

 foreach(var item in mainclass) { List<Class1> result; if (!hs_VersiodIDs.Contains(item.VersionID)) { result = new List<Class1>(.....); } else { result = null; } } 

If the code inside the task really does something expensive, change the code to this:

 var tasks = new List<Task>(); foreach(var item in mainclass) { Task<List<Class1>> cl1Task = Task.Factory.StartNew<List<Class1>>(() => { if (!hs_VersiodIDs.Contains(item.VersionID)) { return new List<Class1>(.....); } else { return null; } }); tasks.Add(cl1Task); } // note, WaitAll is outside the loop, so now our tasks can all run in parallel Task.WaitAll(tasks.ToArray()); 
+2
source

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


All Articles