I am working on a WPF GUI (using MVVM) to control an embedded device. As of yet, the device is still in development and not currently functioning reliably. As such I have created the following fake device:
interface IConnection
{
bool IsValid { get; }
bool Open();
void Close();
void Write(string message);
}
class SerialConnection : IConnection
{
// Not yet implemented
}
class DevConnection : IConnection
{
Timer _timer;
Action<string> _callback;
public bool IsValid {...}
public DevConnection(Action<string> callback)
{
_timer = new Timer(tick, null, Timeout.Infinite, Timeout.Infinite);
_callback = callback;
}
public bool Open() {...}
public void Close() {...}
public void Write(string Message) {...}
private void tick(object args)
{
_callback("V01" + ToHex(vol1) + "\n");
...
}
}
The
Action<string> _callback;
is the function used by my model to read the payload of the connection and update its state appropriately
class Model
{
IConnection _connection;
public Model()
{
_connection = new DevConnection(Message);
}
private void Message(string payload)
{
...
_volume1 = floatValue;
...
}
}
However when the Model is created, I change a bunch of the properties elsewhere before calling Model.IConnection.Open() to start the timer. Every time the Message() callback is called, the debugger shows the Model as still being in its original, constructed state.
1) What is going on behind the scenes here? Is the Threading.Timer creating a new thread for its counting / tick execution? If so, why is it creating a default copy of my Model class?
2) How do I fix it? I even tried giving the DevConnection a copy of my Model class to operate on directly (not how I'd like to setup the architecture) and it still resulted in the same undesired behavior
Unfortunately I have only a rudimentary understanding of the theory of threading, with no idea how to implement it in C#. Tragically I suspect that this issue is a result of thread mis-management.