C # WPF asynchronous Modify UI, multithreaded modify UI (ii)

Source: Internet
Author: User

1. Asynchronous modification using Timers

It's a relatively simple method.

In WPF, timers use Diapatchertimer and do not use the timer reason:

In one application, the timer repeats the time event, and DispatcherTimer is a clock that is integrated into the dispatcher queue, which allows it to be executed periodically at a specified interval with the specified priority.

For a timer clock event, the system is not guaranteed to execute immediately after the time interval arrives, but ensures that it is not executed until the time interval arrives. This is because DispatcherTimer is placed in the dispatcher queue like any other operation. When the DispatcherTimer event is executed depends on the other tasks in the queue and their priority.

If a WPF application uses a timer clock, its events must run in a separate clock thread, not in the UI thread, which is useless for WPF applications-you can't access UI elements directly outside of the UI thread. Instead, the operation can only be sent to the dispatcher object via invoke or BeginInvoke, and the delegate dispatcher to perform the UI operation.

See here, you probably know why we should use DispatcherTimer instead of a timer in WPF: DispatcherTimer and Dispatcher run on--ui threads in the same thread, and have the same dispatcherpriority priority.

Instance:

XAML Code:

<grid><textbox x:name= "textbox" padding= "            height="             textwrapping= "Wrap" text= "TextBox"            Verticalalignment= "Top" margin= "10,105,10,0"/></grid>
Background code:
Start other thread processing, call failed//task.run (() = {//    dispatchertimerhelper.dowork (TextBox);//});// The main thread call succeeds Dispatchertimerhelper.dowork (TextBox);
public class dispatchertimerhelper{    //timer, repeated in the specified event    //In the non-main thread, an exception occurs, the current thread ends the    static DispatcherTimer _ Timer = new DispatcherTimer ();    public static void DoWork (TextBox textBlock)    {        _timer. Interval = new TimeSpan (0, 0, 1);        EventHandler event1 = new EventHandler (Timer_tick);        _timer. Tick + = event1;        _timer. Tag = TextBlock;        _timer. Start ();    }    public static void Stop ()    {        _timer. Stop ();    }    static void Timer_tick (object sender, EventArgs e)    {        DispatcherTimer timer = sender as DispatcherTimer;        TextBox box = timer. Tag as TextBox;        Box. Text = "Zhang San" +datetime.now;    }}

2. Using BackgroundWorker

This class is designed to simplify the threading-related issues of the Windows Form program, and also applies to WPF programs. Suitable for a long-term background process, support progress notification, cancellation support, complete notification and other functions.

Using the method is also simple, creating a Backfruopworker instance that has several events.

The DoWork event is executed in another thread and is started with RunWorkerAsync (). So don't deal with the modification of the interface in this event.

The RunWorkerCompleted event, which is executed on the graph's thread when the DoWork event returns (normal or abnormal return), so you can modify the interface

The ProgressChanged event, which uses the ReportProgress () method call, is executed in the thread of the graphical interface and is usually responsible for modifying the progress bar or something. The ReportProgress () method, which is usually called in the event of DoWork, Then give a percentage value. To use this feature, you need to set the Workerreportsprogress property to True

It is also worth saying that to cancel the support you need to set the Workersupportscancellation property to True, using the CancelAsync () method call, but this call does not terminate the process, So we need to judge cancellationpending in the DoWork event.

Instance:

XAML Code:

<StackPanel>    <progressbar name= "ProgressBar" height= "" "width=", margin=, 10,80,20,10 "></ progressbar>    <button name= "btnprocess" width= "+" click= "Btnprocess_click" margin= "5" > Start background Task </ button>    <button name= "Btncancel" width= "+" click= "Btncancel_click" margin= "5" > Cancel background Tasks </Button>    <label x:name= "label" content= "label" margin= "Ten"/></stackpanel>
C # backend Code:
<summary>///Thread9.xaml's interactive logic///</summary>public partial class thread9:window{BackgroundWorker BG    Worker = new BackgroundWorker ();        Public Thread9 () {InitializeComponent ();        Bgworker.workerreportsprogress = true;        Bgworker.workersupportscancellation = true;        Execute the Task code bgworker.dowork + = Dowork_handler;        Execution Process trigger bgworker.progresschanged + = Progresschanged_handler;    Execution ends, or there is an abnormal end trigger bgworker.runworkercompleted + = Runworkercompleted_handler;        private void Btnprocess_click (object sender, RoutedEventArgs e) {//Start execution if (!bgworker.isbusy)        {Bgworker.runworkerasync (); }} private void Progresschanged_handler (object sender, ProgressChangedEventArgs args) {//In a process change event can be modified within the UI Capacitance progressbar.value = args.        Progresspercentage; Label. Content = "ProgressChanged Method execution Complete" + args.    Progresspercentage; } private void Dowork_handler (object senDer, DoWorkEventArgs args) {//Modifying the UI in DoWork also throws an exception//label.        Content = "DoWork method execution Complete";        BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; i <=; i++) {if (worker. cancellationpending) {args.                Cancel = true;            Break } else {//manual trigger trigger process, code execution worker.                ReportProgress (i);            Thread.Sleep (100); }}} private void Runworkercompleted_handler (object sender, Runworkercompletedeventargs args) {PR        Ogressbar.value = 0; if (args. Cancelled) {MessageBox.Show ("Background task has been canceled.        "," message "); } else {MessageBox.Show ("background task ends normally.        "," message ");     }} private void Btncancel_click (object sender, RoutedEventArgs e) {//End execution Bgworker.cancelasync (); }}

C # WPF asynchronous Modify UI, multithreaded modify UI (ii)

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.