Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better waiting pattern for c#?

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?

like image 350
probably at the beach Avatar asked Aug 09 '11 13:08

probably at the beach


People also ask

Are there any design patterns in C?

There are various patterns in the C language like star patterns, number patterns, and character patterns.

What is the best approach in design pattern in coding?

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.

How many design patterns are there in C#?

This reference provides source code for each of the 23 GoF patterns.


1 Answers

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();   } } 
like image 179
JaredPar Avatar answered Oct 03 '22 04:10

JaredPar