WPF multithreaded Demo

Source: Internet
Author: User
Tags static class
Several ways to work with threads in WPF:

1. Simple DispatcherTimer like a timer control

2. When you need to handle UI synchronization, Dispatcher dispatcheropertion

3. Enhanced Thread Object System.Windows.Threading

4.BackgroundWorker Build Object

Here are a few examples of how to do this: XAML files

<window x:class= "WPF multithreaded Demo. MainWindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml" title= "MainWindow" height= "," width= "525" background= "Bl Anchedalmond "> <Grid> <label content=" UI Multithreading Demo "Fontsize=" height= "margin=" "139,28,205,0" Nam E= "Label1" verticalalignment= "Top"/> <button content= "DispatcherTimer" height= "Notoginseng" margin= "103,73,129,0" Na  Me= "Button1" verticalalignment= "Top" click= "Button1_Click"/> <button content= "Dispatcherthread" Height= "35" Margin= "103,116,129,0" name= "Button2" verticalalignment= "Top" click= "button2_click"/> <button "Content=" Thr EAD "margin=" 103,167,129,111 "name=" Button3 "click=" Button3_Click "/>" <button content= "BackgroundWorker" Hei ght= "margin=" "103,0,129,65" Name= "Button4" verticalalignment= "Bottom" click= "Button4_Click"/> <progressb Ar height= "margin=" 64,0,103,24 "Name=" progressBar1 "verticalalignment=" Bottom "/> <label height=" horizontalalignment= "right" Margin= "0,252,22,0" name= "Label2" verticalalignment= "Top" width= "a"/> </Grid> </Window>

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Windows;
Using System.Windows.Controls;
Using System.Windows.Data;
Using System.Windows.Documents;
Using System.Windows.Input;
Using System.Windows.Media;
Using System.Windows.Media.Imaging;
Using System.Windows.Navigation;
Using System.Windows.Shapes;

Introducing a thread namespace using System.Windows.Threading; Namespace WPF multithreaded Demo {///<summary>///mainwindow.xaml Interactive logic///</summary> public partial CLA
        SS Mainwindow:window {public MainWindow () {InitializeComponent (); }//Mode one DispatcherTimer TM = new DispatcherTimer ()//Instantiate a DispatcherTimer object private void Button1_c Lick (object sender, RoutedEventArgs e) {TM. Tick + = new EventHandler (tm_tick);//Subscribe to Tick Event TM.
            Interval = Timespan.fromseconds (0.05); Tm.
            Start (); Tm.
        Stop (); } void Tm_tick (objecT sender, EventArgs e) {if (progressbar1.value<=100) {Progressbar1.va
                lue++;
            This.label2.Content = progressbar1.value++ + "%"; else {TM.
            Stop (); Mode two public void newactionthread (int value) {THIS.PROGRESSBA R1.
            Value = value;
            This.label2.Content = progressbar1.value++ + "%";
        System.Threading.Thread.Sleep (100); }//Use thread method public void Dispatcherthread () {Dispatcher Newdispatcher = Dispat Cher.

            CURRENTDISPATCHER;//provides a thread working environment action<int> newaction = new action<int> (this.newactionthread);
                for (int i = 0; i < i++) {Newdispatcher.invoke (newaction, i);
                System.Threading.Thread.Sleep (100); This.
                DoEvents (); NewDispatcher.Thread.Abort (); } private void Button2_Click (object sender, RoutedEventArgs e) {dispatcherthread ()
        ; }//mode three public void NewActionThread2 (object value) {action<int> newaction = n
            EW action<int> (This.newactionthread);
        This.progressBar1.Dispatcher.Invoke (newaction, (int) value);//synchronously executes the specified delegate System.Threading.Thread.Sleep (100);
            The thread//System.Threading.Thread in the public void thread () {//winform; Thread//system.windows.threading.dispatcher.currentdispatcher.thread system.threading.p in a WPF environment


            Arameterizedthreadstart ts = new System.Threading.ParameterizedThreadStart (this.newactionthread2);//A thread executes a delegate for (int i = 0; I <= i++) {System.Threading.Thread t = new System.Threading.Thread (t
                s); System.Threading.Thread.
                Sleep (100);
                T.start (i);
                This.label2.Content = progressbar1.value++ + "%"; This. DoEvents ()//Interface Refresh}} private void Button3_Click (object sender, RoutedEventArgs
        e) {Thread (); }//Mode four BackgroundWorker//http://msdn.microsoft.com/zh-cn/library/vstudio/system.componentmodel.background
        worker.aspx more information System.ComponentModel.BackgroundWorker bw; private void Button4_Click (object sender, RoutedEventArgs e) {bw = new System.ComponentModel.Backgrou Ndworker ()///Create BackgroundWorker object instance bw. DoWork + = new System.ComponentModel.DoWorkEventHandler (bw_dowork);//Subscribe to DoWork event bw. ProgressChanged + = new System.ComponentModel.ProgressChangedEventHandler (bw_progresschanged);//Subscribe to report process event bw.
            Workerreportsprogress = true; Bw. RunWorkerAsync ()//start background operation} void Bw_progresschangEd (object sender, System.ComponentModel.ProgressChangedEventArgs e) {this.progressBar1.Value = E.prog
        resspercentage;//get Progress percent This.label2.Content = (e.progresspercentage.tostring () + "%");  } void Bw_dowork (object sender, System.ComponentModel.DoWorkEventArgs e) {for (int i = 0; i <= 100;
                i++) {this.bw.ReportProgress (i);
            System.Threading.Thread.Sleep (100); //Mode 5 We can use thread parallelism to process}}

In the class ex is an extension method. Make interface Refresh

public static class Ex
    {
        //extension method for interface refresh public
        static void DoEvents (this Window win)
        {
            DispatcherFrame frame = new DispatcherFrame ();
            Dispatcher.CurrentDispatcher.BeginInvoke (Dispatcherpriority.background,
                new Dispatcheroperationcallback ( Exitframes), frame);
            Dispatcher.pushframe (frame);

        public static object Exitframes (object f)
        {
            (dispatcherframe) f). Continue = false;
            return null;
        }
    }

Effect Display:


Demo Download: Http://files.cnblogs.com/BABLOVE/WPF%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%BC%94%E7%A4%BA.rar


Reproduced from: http://www.cnblogs.com/BABLOVE/p/3235971.html

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.