sgarcia.dev
sgarcia.dev

Reputation: 6150

What is an efficient way of knowing when an external variable changes?

I'm dealing with a Visual Studio solution that has 2 projects. A main WPF project, and a class library that makes use of an external COM library and simplifies all the code with easier to call methods. I'm trying to keep the code separated, so you could say the class library is a worker project, while my main project has all the UI related code. My problem is while working with variables inside the class library.

I have this variable on the class library that holds an int=0 that changes to 1 if a physical button is pressed on a scanner I purchased. The only way I have of knowing if the button is pressed is checking that variable property, and I need a way to know when it changes. The only idea I have so far is doing:

Thread backgroundThread = new Thread(() => {
   while (variable == 0) { 
       // Do some work, if not;
   thread.Sleep(250); 
   }
});

But this feels inefficient, or so I feel. If I could modify this property I would love to add some code to the Set method to get notified of it changing, but since this is an external COM library's property I have no control over them. Is this the only way I can do this?

Upvotes: 2

Views: 210

Answers (1)

Matt Klein
Matt Klein

Reputation: 8424

In general, there are two ways to know when something has changed:

  • Pull - You pull the value at specific intervals and keep track of the value between calls. If the value has changed, then you perform your "Value Changed" logic.

  • Push - You tell the owner of the value to let you know when the value has changed. You also tell the owner how you want to be notified. The owner will then push the notification to you when the value has changed, usually by calling your "Value Changed" logic for you.

You're currently using the pull method, and you're right to think that it is less efficient than the push method. However, since your code is not in a position to intercept writes to your target variable, then pulling is pretty much all you can do.

Double check the API to make sure there isn't some kind of "Callback" or "Event" listed that is related to the variable that you're interested in. If there is, then you can probably hook into the library there and then be pushed notifications of when the value changes.

If there is no way to get the library to push changes to your code, then you just need to decide how often you want to poll the value. If there isn't much cost to performing the pull, then I'd say that your current 250 ms should be responsive enough that your users feel like the value is being updated in real time.

Further Reading:

How do server-client push/pull connections work?

Data-Pull Model and Data-Push Model

Upvotes: 1

Related Questions