Wednesday, January 28, 2009

Perfect Random numbers


#region Copyright © 2009 Ruben Knuijver [r.knuijver@primecoder.com]
/*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the author(s) be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#endregion

using System;
using System.Threading;

class TaskRnd : IDisposable
{
internal class RandomParam
{
public int Seed { get; set; }
public int minValue { get; set; }
public int maxValue { get; set; }
}

private Thread worker = null;
public delegate void WorkCompleteHandle(int rnd);
public event WorkCompleteHandle OnWorkComplete;

private RandomParam _randomParam = new RandomParam();

public int Seed { set { _randomParam.Seed = value; } }
public int minValue { set { _randomParam.minValue = value; } }
public int maxValue { set { _randomParam.maxValue = value; } }

public TaskRnd()
{
Seed = 1978;
minValue = int.MinValue;
maxValue = int.MaxValue;
}

private void DoWork(Object param)
{
RandomParam p = param as RandomParam;
Random rnd = new Random(p.Seed);
int min = p.minValue,
max = p.maxValue;

while (OnWorkComplete != null)
{
int value = rnd.Next(min, max);

OnWorkComplete(value);
}
}

public void Start()
{
worker = new Thread(new ParameterizedThreadStart(this.DoWork));
worker.Start(_randomParam);
Thread.Sleep(1);
}

#region IDisposable Members

public void Dispose()
{
if (worker.IsAlive)
{
worker.Abort();
worker.Join();
worker = null;
}
}

#endregion
}


Here is how to use the code:

1: using (TaskRnd t = new TaskRnd())
2: {
3: int i = 0;
4: t.maxValue = 255;
5: t.minValue = 0;
6: t.OnWorkComplete += (rnd) => { i = rnd; };
7: t.Start();
8:
9: for (int x = 0; x < 10; x++)
10: {
11: listValues2.Items.Add(string.Format("rnd {0}: {1}", x, i));
12: }
13: }

No comments:

Post a Comment