pro*_*ach 78 c# multithreading design-patterns
我发现自己几次编写这种类型的东西.
for (int i = 0; i < 10; i++)
{
if (Thing.WaitingFor())
{
break;
}
Thread.Sleep(sleep_time);
}
if(!Thing.WaitingFor())
{
throw new ItDidntHappenException();
}
Run Code Online (Sandbox Code Playgroud)
它只是看起来像坏代码,有没有更好的方法这样做/它是一个糟糕的设计的症状?
Jar*_*Par 98
实现此模式的更好方法是让Thing对象公开消费者可以等待的事件.例如a ManualResetEvent或AutoResetEvent.这大大简化了您的消费者代码,如下所示
if (!Thing.ManualResetEvent.WaitOne(sleep_time)) {
throw new ItDidntHappen();
}
// It happened
Run Code Online (Sandbox Code Playgroud)
Thing旁边的代码也没有那么复杂.
public sealed class Thing {
public readonly ManualResetEvent ManualResetEvent = new ManualResetEvent(false);
private void TheAction() {
...
// Done. Signal the listeners
ManualResetEvent.Set();
}
}
Run Code Online (Sandbox Code Playgroud)
Kei*_*thS 12
如果程序在等待时没有其他任何东西可以做(例如在连接到数据库时),则循环不是等待某些东西的可怕方式.但是,我发现你的一些问题.
//It's not apparent why you wait exactly 10 times for this thing to happen
for (int i = 0; i < 10; i++)
{
//A method, to me, indicates significant code behind the scenes.
//Could this be a property instead, or maybe a shared reference?
if (Thing.WaitingFor())
{
break;
}
//Sleeping wastes time; the operation could finish halfway through your sleep.
//Unless you need the program to pause for exactly a certain time, consider
//Thread.Yield().
//Also, adjusting the timeout requires considering how many times you'll loop.
Thread.Sleep(sleep_time);
}
if(!Thing.WaitingFor())
{
throw new ItDidntHappenException();
}
Run Code Online (Sandbox Code Playgroud)
简而言之,上面的代码看起来更像是一个"重试循环",它被认为更像是超时工作.以下是构建超时循环的方法:
var complete = false;
var startTime = DateTime.Now;
var timeout = new TimeSpan(0,0,30); //a thirty-second timeout.
//We'll loop as many times as we have to; how we exit this loop is dependent only
//on whether it finished within 30 seconds or not.
while(!complete && DateTime.Now < startTime.Add(timeout))
{
//A property indicating status; properties should be simpler in function than methods.
//this one could even be a field.
if(Thing.WereWaitingOnIsComplete)
{
complete = true;
break;
}
//Signals the OS to suspend this thread and run any others that require CPU time.
//the OS controls when we return, which will likely be far sooner than your Sleep().
Thread.Yield();
}
//Reduce dependence on Thing using our local.
if(!complete) throw new TimeoutException();
Run Code Online (Sandbox Code Playgroud)
我会看看WaitHandle类。特别是等待对象设置的ManualResetEvent类。您还可以为其指定超时值并检查它是否在之后设置。
// Member variable
ManualResetEvent manual = new ManualResetEvent(false); // Not set
// Where you want to wait.
manual.WaitOne(); // Wait for manual.Set() to be called to continue here
if(!manual.WaitOne(0)) // Check if set
{
throw new ItDidntHappenException();
}
Run Code Online (Sandbox Code Playgroud)