Just sharing some of my inconsequential lunch conversations with you... RSS  

Sunday, April 18, 2010

How to simply starve your windows forms app

I was rewriting on .NET 4 some of our internal benchmarking tools (ok, a cooler way to say I wrote a small utility to stress our components on high concurrent environments…), when I’ve deadlocked the… application itselfe!

Here’s what I’ve done:

            var tasks = Enumerable.Range(1, (int)numericUpDownNumberOfThreads.Value).Select(
i =>
{
var task = new Task(
() =>
{
Invoke(LogMessageDelegate, ">> I'm in: " + i);
Thread.Sleep(new Random().Next(1000));
Invoke(LogMessageDelegate, "<< Bye bye: " + i);
}
);
task.Start();

return task;
}
).ToArray();

Invoke(this.LogMessageDelegate, ">> WaitAll");
Task.WaitAll(tasks);
Invoke(this.LogMessageDelegate, "<< WaitAll");


The way the Invoke method works is quite simply by sending a message to the correct thread, and if there is no message pumping no one will process the message. The solution was evolving on yet another thread:


            new Task(
() =>
{
var tasks = Enumerable.Range(1, (int)numericUpDownNumberOfThreads.Value).Select(
i =>
{
var task = new Task(
() =>
{
Invoke(LogMessageDelegate, ">> I'm in: " + i);
Thread.Sleep(new Random().Next(1000));
Invoke(LogMessageDelegate, "<< Bye bye: " + i);
}
);
task.Start();

return task;
}
).ToArray();

Invoke(this.LogMessageDelegate, ">> WaitAll");
Task.WaitAll(tasks);
Invoke(this.LogMessageDelegate, "<< WaitAll");
}
).Start();

No comments:

Development Catharsis :: Copyright 2006 Mário Romano