Tasks in C # - an incomprehensible result using Random

I study asynchronous programming in C # and wrote this code to test a parallel task library (console application):

static void Main(string[] args)
{
    Stopwatch sw = new Stopwatch();

    var opr1 = new SlowOperation();
    var opr2 = new SlowOperation();

    //TASK
    Console.WriteLine("Started processing using TASK. Start: {0}", sw.Elapsed);
    sw.Start();

    Task.Factory.StartNew(() => opr1.PerformSlowOperation(1));
    Task.Factory.StartNew(() => opr2.PerformSlowOperation(2));

    Console.WriteLine("Stopped processing using TASK. Stop: {0}", sw.Elapsed);
    sw.Stop();

}

where is the slow operation:

public class SlowOperation
{
    public void PerformSlowOperation(int id)
    {
        var rand = new Random();
        double sum = 0;

        for (int i = 0; i < 100000000; i++)
        {
            var number = Convert.ToDouble(rand.Next(100)) / 100;
            sum += number;
        }
        Console.WriteLine("Finished processing operation no. {0}. Final sum calculated is: {1}", id, sum.ToString("0.##"));
    }
}

Can someone help me understand why the amount created by each instance of the SlowOperation class is exactly the same?

+4
source share
2 answers

Randomseeded on the basis of time with low resolution. This is a classic problem and, in my opinion, an API design error. I think this has already been changed in the CoreCLR repository.

new Random().Next() == new Random().Next() almost always true.

, 95% . , . .

+2

. :

var rand = new Random(new System.DateTime().Millisecond + id);

: https://msdn.microsoft.com/pt-br/library/ctssatww(v=vs.110).aspx

, . , . , . .

+2

All Articles