WPF thread--dispatcher

Source: Internet
Author: User

When you use WPF development, you often encounter threads that you create that need to update the interface UI content, resulting in cross-threading issues.

Exception content:

Exception type: System.InvalidOperationException

Exception Description:

Unhandled exception of type "System.InvalidOperationException" occurs in WindowsBase.dll

Additional information: The calling thread cannot access this object because another thread owns the object.

One of the easiest ways to solve this problem in WPF is to use dispatcher.

1, the most convenient use of dispatcher

This. Dispatcher.invoke (New action (() = {//do something//update UI Action})); Thread.Sleep (100);

2. Using the dispatcher of the control itself "in WPF, the control finally inherits from the Dispatcherobject"

if (!this.pb_test. Dispatcher.checkaccess ()) {//Update UI interface This.pb_test. Dispatcher.invoke (Dispatcherpriority.normal, new updateprogressbardelegate (int progress) = {This.pb_test. Value = Progress;}), i); Thread.Sleep (100);}

3, with 2, using the dispatcher of the current form

if (! Dispatcher.checkaccess ()) {Dispatcher.invoke (dispatcherpriority.normal,new updateprogressbardelegate (int Progress) = {This.pb_test. Value = Progress;}), i); Thread.Sleep (100);}

Project Escrow Address: https://wpfthread.codeplex.com/

WPF thread--dispatcher

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.