Change viewmodel property from another thread

Please help me with advice or demo code for the following task:

I had a program in WPF that constantly listens on a serial port. If he received a specific signal, he should change the property in the ViewModel. The listener starts in another thread, so I was wondering how I can change the ViewModel property from another thread, I'm trying to pass the property by reference, but that was not possible.

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    //My property in the view model
    private Boolean _Lock;
    public Boolean Lock
    {
        get { return _Lock; }
        set
        {
            _Lock = value;
            OnPropertyChanged("Lock");
        }
    }

 //Start the listener thread
        Thread ComListenThread = new Thread(delegate() 
            {                  
                Com cm = new Com(Path,Lock);                    
                cm.Start();                    
            });
        ComListenThread.Start();


class Com
{

    private Uri web { get; set; }
    private Boolean Lock { get; set; }

    public Com(Uri Path,Boolean _Lock)
    {
        web = Path;                                
        Lock = _Lock;                                              
    }


    public void Start()
    {
        try
        {
            port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);

        }
        catch (Exception e)
        {
            MessageBox.Show("Reason {0}:", e.Message);
        }

        port.ReadTimeout = 500;
        port.Open();

        int position = 0;            
        while (true)
        {

            try
            {
                int len = port.Read(data, position, data.Length - position);
                position += len;
            }
            catch (TimeoutException)
            {


                //How to change Lock property 
                Lock = (data[2]==5)?true:false;


                position = 0;
            }
        }
    }                      
}

So my question is how to pass a property that will be changed in another thread in a constant loop.

+3
source share
1 answer

, ; (Dispatcher.Invoke), , "" .

, ( ) UI . "" ( " " ), , .

+3

Source: https://habr.com/ru/post/1790158/


All Articles