Your code makes no sense for two reasons:
- Starting a task that doesn't contain any long running code is useless. You will gain no advantage from this
- Waiting for the task to finish right after starting it, completely negates the effect of the task: You are still blocking your main thread.
Change your code to this if the code in the task really is that 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 your 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());