-2

I need my threads to generate different randoms every time, but some are not that random, as they're the same as previous ones.

Already saw some answers about this but I'm not familiar with c# and the way I have the code is not fully compatible with it.

Please note that I'm starting c# and even tho it could be simple, to adapt, I just don't know how.

I've tried to use

static int seed = Environment.TickCount;
static readonly ThreadLocal<Random> random =
new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));

But without success... Don't really know where I should use it.

This is my code for now.

for (var i = 0; i <= loopTo; i++)
{
    var trd = new Thread(() =>
    {
        while (go != 0)
        {
            try
            {
                int count = 0;
                string c1 = "";
                string pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
                Random cc = new Random();
                int strpos = 0;
                while (count <= 3)
                {
                    strpos = cc.Next(0, pool.Length);

                    c1 = c1 + pool[strpos];
                    count = count + 1;
                }

                // SOME MORE CODE
            }
            catch (WebException ex)
            {

            }
        }
    });
    trd.IsBackground = true;
    threads.Enqueue(trd);
    trd.Start();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Also you might want to take a look at https://learn.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.7.2#the-systemrandom-class-and-thread-safety if this and the above duplicates don't answer your question please edit to include what you have tried, what part is not working, why you don't understand them, so we can help you further – TheGeneral Dec 21 '18 at 05:56
  • "Random" does not mean unique: It means _unpredictable_. In general, one of the things you will not be able to predict about the next number in a random sequence is whether or not it will be equal to any previous number in the sequence. (Though, if there's only a finite number of possible values, and if you wait long enough, you'll get to the point where _every_ next value must be equal to some previous value.) – Solomon Slow Dec 21 '18 at 15:45
  • Thank you Taw but i mentioned that i did search and i did find something but maybe I'm not applying it in the right place. – Vasco Teixeira Dec 21 '18 at 16:08
  • You are right Solomon, although i don't get one or two in a long space of time. I get duzens of them straight. It seems that random() works with the clock and, as i have usually +300 threads like that, it generates the same. – Vasco Teixeira Dec 21 '18 at 16:09

1 Answers1

-1

You can simply use below code. This will ensure you will never get duplicate random string.

  string randromString = Guid.NewGuid().ToString();
Ankush Jain
  • 5,654
  • 4
  • 32
  • 57