views:

543

answers:

2

How would you recommend I setup an event handler to fire when a variable is updated with a value > 0.

public _price;

public double GetPrice(string item)
{
    _table.GetData += new EventHandler<EventArgs>(ExtractData);

    // Right now I set it to sleep to give it enough time to return the data.
    // But I would like to setup an eventhandler to return the _price when a value is populated
    Thread.Sleep(1000);

    return _price;
}

void ExtractData(object sender, DataEventArgs e)
{
    foreach (PriceRecord rec in e)
    {
        if (rec.myprc != null)
            {
                 _price = double.Parse(rec.myprc.Value.ToString());
            }
    }
}

If I remove Sleep it doesn't have enough time to get the data before returning an incorrect value. I would like to remove sleep to increase performance and just for my own knowledge. If there are better alternatives than using an event handler Im open to suggestions.

Any suggestions or advice you have is appreciated, Thank you.

+5  A: 

Your design... there is something wrong with it.

You cannot block the execution of a method with an event, so I don't think that would be a good solution here.

Are you multithreading where it says //Some code here? If so, check into Thread.Join (if you're using a heavyweight thread) or a Monitor (if you're using the thread pool) to block he execution of GetPrice until a value has been set.

Without the details of what you're doing I'm not sure if there is a better solution.

Will
Excellent, thank you.
Leroy Jenkins
I wish you'd shown a little more about the design; there is probably a much better (and simpler) way to do this.
Will
+1  A: 

http://ondotnet.com/pub/a/dotnet/2002/04/15/events.html

Very useful article!

WhiteD