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:
Post a Comment