Wpf asynchronously updates viewer data in presenter (VM)

Source: Internet
Author: User
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.