Child tasks not expected by parent

This is my code.

static void Main(string[] args)
{
    List<Thing> collection = new List<Thing>
    { 
        new Thing { IntProp = 1, BoolProp = true }, 
        new Thing { IntProp = 1, BoolProp = true }, 
        new Thing { IntProp = 2, BoolProp = true }, 
        new Thing { IntProp = 1, BoolProp = false } 
    };

    int number = 0;

    var task = Task.Factory.StartNew<bool>(() =>
    {
        TaskFactory ts = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);

        foreach (var item in collection)
        {
            if (item.BoolProp)
            {
                ts.StartNew(() =>
                    number += GetNum1(item.IntProp));
            }
            else
            {
                ts.StartNew(() =>
                    number += GetNum2(item.IntProp));
            }
        }

        return true;
    });

    task.Wait();

    Console.WriteLine(number);
}

there are definitions GetNum1andGetNum2

static int GetNum1(int num)
{
    for (int i = 0; i < 1000000000; i++) { } // simulate some job

    return 10;
}

static int GetNum2(int num)
{
    for (int i = 0; i < 500000000; i++) { } // simulate some job

    return 3;
}

and here is the class Thing

class Thing
{
    public bool BoolProp { get; set; }
    public int IntProp { get; set; }
}

basically what i am doing is just creating a collection of objects Thing. then I create one parent task that will have several child tasks (which it should wait for, I think).

number, , GetNum1 GetNum2 (10 3). 33 (10 + 10 + 10 + 3), , 10, . , . . - foreach ? , " " " ", .

+4
1

( "" ) . , number :

var mutex = new object();
int number = 0;

var task = Task.Factory.StartNew<bool>(() =>
{
    TaskFactory ts = new TaskFactory(TaskCreationOptions.AttachedToParent, TaskContinuationOptions.ExecuteSynchronously);

    foreach (var item in collection)
    {
        if (item.BoolProp)
        {
            ts.StartNew(() =>
            {
                var value = GetNum1(item.IntProp);
                lock (mutex) number += value;
            });
        }
        else
        {
            ts.StartNew(() =>
            {
                var value = GetNum2(item.IntProp);
                lock (mutex) number += value;
            });
        }
    }

    return true;
});

task.Wait();

lock (mutex)
    Console.WriteLine(number);

: Parallelism.

+5

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


All Articles