Leroy Jenkins
Leroy Jenkins

Reputation: 2770

Using an EventHandler to detect a variable change?

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.

Upvotes: 0

Views: 4961

Answers (2)

WhiteD
WhiteD

Reputation: 21

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

Very useful article!

Upvotes: 2

user1228
user1228

Reputation:

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.

Upvotes: 5

Related Questions