I've found myself coding this type of thing a few times.
for (int i = 0; i < 10; i++) { if (Thing.WaitingFor()) { break; } Thread.Sleep(sleep_time); } if(!Thing.WaitingFor()) { throw new ItDidntHappenException(); }
It just looks like bad code, is there a better way of doing this / is it a symptom of bad design?
There are various patterns in the C language like star patterns, number patterns, and character patterns.
One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic. The only problem with a factory method is it relies on the concrete component.
This reference provides source code for each of the 23 GoF patterns.
A much better way to implement this pattern is to have your Thing
object expose an event on which the consumer can wait. For example a ManualResetEvent
or AutoResetEvent
. This greatly simplifies your consumer code to be the following
if (!Thing.ManualResetEvent.WaitOne(sleep_time)) { throw new ItDidntHappen(); } // It happened
The code on the Thing
side is also not really any more complex.
public sealed class Thing { public readonly ManualResetEvent ManualResetEvent = new ManualResetEvent(false); private void TheAction() { ... // Done. Signal the listeners ManualResetEvent.Set(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With