bitwix

Tangential comments about Software Development

Saturday, January 21, 2006

A Random Number Web Service - Keeping It Honest

Two things Microsoft have made easy for us these days. Writing a web service and producing random numbers. But do they work together?

Web services are new(ish) so it's no surprise that the authoring tools are getting easy to use. Visual Studio 2005 does get you from zero to hero in minutes. If you skip documentation paragraphs (as I do), then the only gotcha is that yes, you have to run WSDL from the VS2005 command line prompt.

Random number generators have been around for years. We've all used them for silly programs. Most of us have then noticed that to start with they actually gave us the same stream of "random" numbers, so we read up about seeding and then found a way that was random enough to seed the generator so that we never saw the same sequence twice.

We were therefore pleased that in the .Net Framework
Random r = new Random();
used a seed generated from the time. So we could just use that and *bingo* our numbers were never the same twice.

Put these two technologies together, and you have a random number generating web service.

Except you don't. Use the service twice on a page, and you get the same number.

The problem is that each call to the web service creates a new Random() class object, seeded with the current time. Call it quickly enough, and the next one will be seeded with the same time, and it's no longer random.

My solution was to pause for a tick before creating the Random object. I did this by holding the DateTime.Now.Ticks and then sleeping the thread for 1 millisecond.
using System.Threading;

public class RandomData
: System.Web.Services.WebService
{
Random m_r;
public RandomData ()
{
long tc = DateTime.Now.Ticks;
do
{
Thread.Sleep(1);
} while (tc == DateTime.Now.Ticks);
m_r = new Random();
}
You can then use m_r.Next() without fear.

Why do you want a random number web service? So that it can become a full random data web service, applying algorithms or reading databases of potential values. See www.bitwix.com/NorMad for more.