I came across an easy way to get rid of some boiler plate code I am always writing when writing event handlers. Consider this example:
public event EventHandler SomethingHappened;
private void OnSomethingHappened() {
var handler = SomethingHappened;
if (handler != null) {
handler(this, EventArgs.Empty);
}
}
In the OnSomethingHappened() method there's a lot of unnecessary boiler plate code to make sure that we don't run into a NullReferenceException.
With a small change to the setup we can do the same with much less coding. Consider another improved example:
public event EventHandler SomethingElseHappaned = delegate { };
private void OnSomethingElseHappened() {
SomethingElseHappened(this, EventArgs.Empty);
}
That was easy! I'm gonna do this from now on!
Happy coding!
This blog is mainly meant as my own notepad where I can put tips and tricks about software development.
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Monday, September 22, 2014
Monday, January 21, 2013
How to check if a WaitHandle is set
Say you have a wait handle of type EventWaitHandle and want to check if it is set or not. To do this call the WaitOne(int) method with a timeout of zero. It will return true if the wait handle is set and false otherwise.
Example
using System; using System.Threading; namespace ConsoleApp { public class Program { /// <summary> /// Running this program will output /// Wait handle is not set /// Wait handle is set /// to the console. /// </summary> public static void Main(string[] args) { var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); Console.WriteLine(waitHandle.WaitOne(0) ? "Wait handle is set" : "Wait handle is not set"); waitHandle.Set(); Console.WriteLine(waitHandle.WaitOne(0) ? "Wait handle is set" : "Wait handle is not set"); } } }
Subscribe to:
Posts (Atom)