I have application where user provides data to be handled by thread and then the thread returns the data into the UI. User can change the input starting another thread. How to properly ignore old returing threads ?
I noticed two solutions often desribed. 1) in the invoke check if current input data is same as the thread worked on 2) wait for first thread to end before starting another one
first solution works but still older thread may be used if user changed input again to same value and I get twice or more refreshing UI with the same data second option is less responsive especially when the calculations in thread run longer because we have to wait for each thread to complete its work
I created below solution and I wonder if it is proper way of handling it or I need to add some other check or lock.
private Thread lastThread;
private void ButtonClick(object sender, MouseButtonEventArgs e)
{
this.lastThread= new Thread(delegate () { Update(someData); });
this.lastThread.Start();
}
private void Update(int someData) {
Thread currThread = Thread.CurrentThread;
Application.Current.Dispatcher.Invoke(new Action(() => EndUpdate(
someDataCalculated,
currThread
)));
private void EndUpdate(int someDataCalculated, Thread senderThread) {
if (senderThread == this.lastThread)
{
// right thread, do some work in UI
}
}