WPF多线程演示

50 篇文章 2 订阅
28 篇文章 0 订阅
本文介绍了WPF中实现多线程的四种方法:使用DispatcherTimer、Dispatcher与Thread结合、增强的Thread对象以及BackgroundWorker组件,并通过实例展示了如何在UI上更新进度。
摘要由CSDN通过智能技术生成

转载地址:http://blog.csdn.net/jumtre/article/details/17028657

 

WPF中的几种处理线程的工作方式:

1.简单的DispatcherTimer类似Timer控件

2.需要处理UI同步时,Dispatcher DispatcherOpertion

3.增强的Thread对象  System.Windows.Threading

4.BackgroundWorker组建对象

下面看下展示着几种处理方式:xaml文件

<Window x:Class="WPF多线程演示.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Background="BlanchedAlmond">
    <Grid>
        <Label Content="UI多线程演示" FontSize="24" Height="49" Margin="139,28,205,0" Name="label1" VerticalAlignment="Top" />
        <Button Content="DispatcherTimer" Height="37" Margin="103,73,129,0" Name="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="Thread" Margin="103,167,129,111" Name="button3" Click="button3_Click" />
        <Button Content="BackgroundWorker" Height="40" Margin="103,0,129,65" Name="button4" VerticalAlignment="Bottom" Click="button4_Click" />
        <ProgressBar Height="35" Margin="64,0,103,24" Name="progressBar1" VerticalAlignment="Bottom" />
        <Label Height="35" HorizontalAlignment="Right" Margin="0,252,22,0" Name="label2" VerticalAlignment="Top" Width="60" />
    </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;
//引入线程命名空间
using System.Windows.Threading;

namespace WPF多线程演示
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        //方式一
        DispatcherTimer tm = new DispatcherTimer();//实例化一个DispatcherTimer对象
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            tm.Tick += new EventHandler(tm_Tick);//订阅Tick事件
            tm.Interval = TimeSpan.FromSeconds(0.05);
            tm.Start();
            // tm.Stop();
        }

        void tm_Tick(object sender, EventArgs e)
        {
            if (progressBar1.Value<=100)
            {
                progressBar1.Value++;
                this.label2.Content = progressBar1.Value++ +"%";
            }
            else
            {
                tm.Stop();
            }
          
        }

        //方式二
        public void newActionThread(int value)
        {
            this.progressBar1.Value = value;
            this.label2.Content = progressBar1.Value++ + "%";
            System.Threading.Thread.Sleep(100);
        }
      
        // 使用线程 方法
        public void DispatcherThread()
        {
            Dispatcher newDispatcher = Dispatcher.CurrentDispatcher;//提供线程工作环境
            Action<int> newAction = new Action<int>(this.newActionThread);

            for (int i = 0; i < 100; i++)
            {
                newDispatcher.Invoke(newAction, i);
                System.Threading.Thread.Sleep(100);
                this.DoEvents();
                //   newDispatcher.Thread.Abort();
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            DispatcherThread();
        }

        //方式三

        public void newActionThread2(object value)
        {
            Action<int> newAction = new Action<int>(this.newActionThread);
            this.progressBar1.Dispatcher.Invoke(newAction, (int)value);//同步执行指定的委托
            System.Threading.Thread.Sleep(100);
        }
        public void Thread()
        {
            //winform中的线程
            //  System.Threading.Thread;
            //wpf环境中的线程
            //System.Windows.Threading.Dispatcher.CurrentDispatcher.Thread
            System.Threading.ParameterizedThreadStart ts = new System.Threading.ParameterizedThreadStart(this.newActionThread2);//一个线程执行委托


            for (int i = 0; i <= 100; i++)
            {
                System.Threading.Thread t = new System.Threading.Thread(ts);
                System.Threading.Thread.Sleep(100);
                t.Start(i);
                this.label2.Content = progressBar1.Value++ + "%";
                this.DoEvents();//界面刷新

            
            }
        }
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            Thread();
        }
        //方式四BackgroundWorker
        //http://msdn.microsoft.com/zh-cn/library/vstudio/system.componentmodel.backgroundworker.aspx更多信息
        System.ComponentModel.BackgroundWorker bw;
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            bw = new System.ComponentModel.BackgroundWorker();//创建BackgroundWorker对象实例
            bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);//订阅DoWork事件
            bw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(bw_ProgressChanged);//订阅报告进程事件
            bw.WorkerReportsProgress = true;
            bw.RunWorkerAsync();//开始执行后台操作
          
        }

        void bw_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage;//获取进度百分比
            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);
            }

        }
        //方式5我们可以利用线程并行来处理
    }
}


类EX中的是一个扩展方法。进行界面刷新

 public static class Ex
    {
        //扩展方法进行界面刷新
        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;
        }
    }


效果展示:


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值