In MVP or MVVM mode, VM and Presenter exchange data with Viewer through binding. In actual projects, you often need to dynamically refresh the interface data. I usually refresh the bound property changes. However, asynchronous updates are required when the data volume is large or the number of updates is frequent. The following provides a safer method to achieve this purpose.
First, define the distributor. It provides services for managing thread work item queues
Private readonly Dispatcher _ dispatcher = Dispatcher. CurrentDispatcher;
Second, define the timer.
_ DataUpdateTimer = new DispatcherTimer ();
_ DataUpdateTimer. Interval = new TimeSpan (0, 0, 0, 0,500 );
_ DataUpdateTimer. Tick + = new EventHandler (OnUpdateTimerTick );
ID of the recording thread
_ ThreadId = Thread. CurrentThread. ManagedThreadId;
The last part is the update part. The main function is to assign a random value to the binding attribute on the interface.
Private readonly Random _ random = new Random (int) DateTime. Now. Ticks );
Private void OnUpdateTimerTick (object sender, EventArgs e)
{
If (_ threadId = Thread. CurrentThread. ManagedThreadId) return;
// The CheckAccess method can verify whether the thread can be accessed;
// When using Winform, SelfSynchronizationContext = SynchronizationContext. Current & InvokeRequired = false
If (! _ Dispatcher. CheckAccess ())
{
_ Dispatcher. BeginInvoke (new ThreadStart () =>
{
UIValue = _ random. NextDouble () * 10000/DateTime. Now. Millisecond;
}), Null );
Return;
}
UIValue = _ random. NextDouble () * 10000/DateTime. Now. Millisecond;
}