Nick Tsui
Nick Tsui

Reputation: 634

How to monitor the change of a variable from another dll?

Here is what I have not figured out: I want my main program to monitor a variable from another dll(thread); This variable is a bool flag that varies between true and false depending on the external hardware trigger. Here is what I did, but apparently it was not responding to the change of the variable:

public bool IsTriggerOn
{
    get { return TriggerWatcherDll.IsTriggerOn; }
    set
        {
             _isTriggerOn= TriggerWatcherDll.IsTriggerOn = value;
             if (_isTriggerOn == true)
             {
                  System.Windows.Forms.MessageBox.Show("Trigger is ON!");
             }
         }
}

How exactly should I do this? Thanks.

I am using C# + WPF, and the code above is from a C# code behind a xaml;

Upvotes: 0

Views: 1660

Answers (1)

Ian Yates
Ian Yates

Reputation: 941

It looks like you might be confusing yourself slightly. The fact that the TriggerWatcherDll class is in a different assembly does not appear to be relevant, based on the code sample you've given.
In fact, it looks like you are accessing IsTriggerOn as a static property of the class (based on the naming used), so the different thread is also not relevant to detecting the change (although, race conditions are a possibility).

From what you've described, it sounds like you just need an event in your "other" DLL:

class TriggerWatcherDll
{
    public static event EventHandler TriggerChanged;

    private static bool _trigger = false;
    public static bool IsTriggerOn
    {
        get { return _trigger; }
        set
        {
            if (_trigger != value)
            {
                _trigger = value;
                if (TriggerChanged != null)
                    TriggerChanged.Invoke(null, new EventArgs());
            }
        }
    }
}

Then just subscribe to the event in your main DLL:

class OtherDll
{
    public OtherDll()
    {
        TriggerWatcherDll.TriggerChanged += TriggerWatcherDll_TriggerChanged;
    }

    void TriggerWatcherDll_TriggerChanged(object sender, EventArgs e)
    {
        if (TriggerWatcherDll.IsTriggerOn)
            System.Windows.Forms.MessageBox.Show("Trigger is ON!");
    }
}

You might want to reconsider your use of static, though, and I haven't touched on threading problems.

Upvotes: 2

Related Questions