There is a WPF application, used for dispensing liquids. With each new dosing, it is necessary to check whether the capacity under the dosing unit has changed, and if not, display a message about the need to change the capacity. There is such a code
public bool CheckChangeCupInThread() { if (_dispenser.Status.CupChanged == DispenserEnums.CupChanged.False) { var cupFormThread = new ThreadStart(CupWaitChangeForm); var cupFormWaiter = new Thread(cupFormThread) {IsBackground = true}; cupFormWaiter.SetApartmentState(ApartmentState.STA); var cupThread = new ThreadStart(WaitForCupChange); var cupWaiter = new Thread(cupThread) {IsBackground = true}; cupWaiter.SetApartmentState(ApartmentState.STA); cupFormWaiter.Start(); cupWaiter.Start(); do { //Wait for Cup to be changed or Cancel } while (cupFormWaiter.IsAlive && cupWaiter.IsAlive); var watch = new Stopwatch(); watch.Start(); if (cupFormWaiter.IsAlive) { cupFormWaiter.Abort(); cupFormWaiter.Join(); } if (cupWaiter.IsAlive) { _dispenser.SurveillanceWorker.Continue = false; cupWaiter.Join(200); return false; } watch.Stop(); } return true; } private void WaitForCupChange() { do { _dispenser.GetStatus(); } while (_dispenser.Status.CupChanged == DispenserEnums.CupChanged.False); } private void CupWaitChangeForm() { MessageBox.Show("Change please the cup", "Cup сhange", MessageBoxButtons.Cancel); } here _dispenser itself is the dispenser. The principle is this: either the capacitance is changed, or the Cancel button in the MessageBox is pressed, the threads end with the corresponding result. Everything seems normal at first glance. But very often this code causes the program to crash. I tried to do the same with tasks, but somehow it didn’t work out well, I’m new to multithreaded applications. I work with WPF and MVVM pattern.
Task? Or what? - BulsonSetApartmentStatetin ... Why two threads,SetApartmentState, empty loop, re-check onIsAlive? - Raider