Search This Blog

Saturday, April 28, 2012

Using EventWaitHandle to Wait for Delegates

[C# - WinForms - .NET 2.0+]


I recently had a to create a database query queue system in an very complicated exisiting application. I wanted to make something quickly that would not break the exisitng modules that relied on the old method until I could go through each individual function that required change. The old way was to run a query and return  a DataSet object. The new way queued each request and returned the DataSet via a delegate. This required that the original method create a query object, use an inline delegate and then wait until the delegate fired before it could continue. Basically I wanted to make an asynchronous operation synchronous. Welcome the EventWaitHandle object.

The code below is a snippet of the actual method I used. It adds an item to the queue and use the WaitOne() method of the EventWaitHandler object to wait for a signal which is fired as soon as the delegate is called.


public DataSet RunDSQuery(string query)
{
    EventWaitHandle signal = new EventWaitHandle(false, EventResetMode.ManualReset);
    DataSet ds = null;

    DatabaseQueueItem queueItem = new DatabaseQueueItem();
    queueItem.Command = this.DbConnection.CreateCommand();
    queueItem.Command.CommandText = query;
    queueItem.Result_Callback = delegate(object sender, DataSet cbds, Exception cbex)
    {
        ds = cbds;       
        signal.Set();
    };

    _DatabaseQueue.Add(queueItem);

    signal.WaitOne();  
    return ds;
}