I have an issue where I have a normal function, that calls an async function, that calls another async function in a loop. Problem is, there are calls to my hardware interface (such as Scan which performs motor movements) and for some reason, this seems to block the UI thread continuously until we actually finish executing the entire "Start" function.
I'm not sure what I'm doing wrong, but I feel maybe certain parts shouldn't be done on the UI thread and maybe done on another thread... I'm not entirely sure how to do this. Below is an example of the code. With each scan, the UI does get updated where the "button" is highlighted per scan.
public void StartProcess(ObservableCollection<ObjModel> objs)
{
// Cancel
if (cancellationTokenSource != null)
{
// Cancel tasks
cancellationTokenSource.Cancel();
cancellationTokenSource.Dispose();
return;
}
cancellationTokenSource = new CancellationTokenSource();
if (MachineController.Instance.InitHardware())
{
StartScan(objs);
}
else
{
Clean();
}
}
private async void StartScan(ObservableCollection<ObjModel> objs)
{
// We are now running
InfoModel.IsRunning = true;
for (int index = 1; index < Size; index++)
{
MachineController.Instance.MoveToIndex(index - 1);
if ((index - 1) % 2 == 0)
{
for (int iAIndex = 1; iAIndex < Size; iAIndex++)
{
var obj = objs.Where(x => x.R == index && x.C == iAIndex).FirstOrDefault();
await DoScan(obj);
}
}
}
Clean();
}
private async Task DoScan(ObjModel obj)
{
MachineController.Instance.MoveToCIndex(obj.C - 1);
// Set the task to only take a couple of seconds
bool check = MachineController.Instance.Scan();
if (check)
{
await Task.Delay(5, cancellationTokenSource.Token);
// Plot
UpdateGraph(obj.R, obj.C);
}
}