MainWindowViewModel
public void MainWindowViewModel()
{
var ports = LoadInstruments();
if (ports.Count == 0) //ports.Count = 0 when NOT stepping through.
{
//DoSomething
}
else
{
Instruments=ports;
}
}
Public ObservableCollection<Instrument> LoadInstuments()
{
InstComs inst=new();
return inst.GetInstPortsAsync(); //Also tried awaiting this.
}
in InstComs Class
public async Task<ObservableCollection<InstrumentViewModel>> GetInstrumentPortsAsync()
{
ObservableCollection<InstrumentViewModel> ports = new();
foreach (string port in SerialPort.GetPortNames())
{
SerialPort sp = new()
{
PortName = port,
ReadBufferSize = 1024,
DiscardNull = true,
RtsEnable = true,
DtrEnable = true,
ReceivedBytesThreshold = 1,
BaudRate = 9600,
StopBits = StopBits.One,
Parity = Parity.None,
DataBits = 8
};
try
{
sp.Open();
if (sp.IsOpen)
{
string instID = await Task.Run(()=> GetInstrumentId(sp));
if (instID != null)
{
if (instID.ToString().Contains("InstNo"))
{
InstrumentViewModel ivm = new();
ivm.Parity = sp.Parity;
ivm.StopBits = sp.StopBits;
ivm.InstID = instID.ToString().Split(',').ElementAt(2);
ivm.BaudRate = sp.BaudRate;
ivm.PortName = sp.PortName;
ivm.DataBits = 8;
ivm.RTSEnabled = sp.RtsEnable;
ivm.DTREnabled = sp.DtrEnable;
ivm.Port = sp;
ivm.IsConnected = true;
ports.Add(ivm);
}
}
}
}
catch (InvalidOperationException)
{
//Handle it
}
}
return ports;
}
Public Task<string> GetInstrumentID(string port)
{
try
{
string response = string.Empty;
sp.WriteLine("*IDN?");
while (sp.BytesToRead > 0)
{
respose += sp.ReadExisting();
}
return response.Replace("\r", "").Trim();
}
catch
{
//Do the catch stuff
}
}
When I step through the code, it works perfectly. The instrument is returned and appears in the list view in the main view with all of the data. If I just run it (in debug mode) the instruments collection remains empty. The MainWindowView has a ListView that is bound to the Instruments collection.
Yes, a lot of code has been removed or left out. But none of it has a bearing on the way this behaves. I have tried awaiting GetInstrumentID. I have tried awaiting GetInstrumentPorts. None of it makes a difference. I have even tried a pause using Thread.Sleep(1000) to slow things down and that didn't help.
Any ideas?
Thanks,