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); }
source share