4
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 );
}

It does not wait for task to finish. The problem is with return null so how can I return empty task ?

1 Answer 1

2

Your code makes no sense for two reasons:

  1. Starting a task that doesn't contain any long running code is useless. You will gain no advantage from this
  2. 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());
Sign up to request clarification or add additional context in comments.

11 Comments

its not full code just the issue is coming when i return null
@Haider Then please show a minimal example that demonstrates the problem. There's nothing magical about "return null;", that by itself isn't the cause of whatever problem you're having.
sORRY.the problem was not in this function but in parallel.foreach i was adding to list in it and some how one two values were null used concurrentbag and all is working fine but performance is low . one again sorry to all
@Haider: "Performance is low" - I suggest you read my answer again and try to understand specifically the second reason for why your code makes no sense.
@Haider: In that case you forgot nearly every important detail in your question... Please keep this in mind for your next one.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.