Threading WPF

来源:互联网 发布:淘宝灯饰 编辑:程序博客网 时间:2024/05/22 13:08
using System;
using System.IO;
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.Threading;
using Microsoft.Win32;
using System.Threading;


namespace ThreadTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        System.Threading.Thread timeThread;
        System.Threading.Thread copyThread;
         
        


        public MainWindow()
        {
            InitializeComponent();


            this.displaytimebythread.Text = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日 hh:mm:ss");
            timeThread = new System.Threading.Thread(new ThreadStart(DispatcherThread));
        }


        public void DispatcherThread()
         {
             //可以通过循环条件来控制UI的更新
              while (true)
            {
                ///线程优先级,最长超时时间,方法委托(无参方法)                
                displaytimebythread.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,new Action(UpdateTime));
                System.Threading.Thread.Sleep(1000);                
             }
         }


        private void UpdateTime()
          {
              this.displaytimebythread.Text = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日 hh:mm:ss");      
         }


        private void Window_Closed(object sender, EventArgs e)
        {
            ///关闭所有启动的线程
            timeThread.Abort();
            copyThread.Abort();
            Application.Current.Shutdown();
        }


        private void Button1_Click(object sender, RoutedEventArgs e)
        {
             ///设定要复制的文件全路径           
            OpenFileDialog openFile = new OpenFileDialog();
            openFile.AddExtension = true;
            openFile.CheckPathExists = true;
            openFile.Filter = "*.rar|*.rar|all files|*.*";
            openFile.FilterIndex = 0;
            openFile.Multiselect = false;
            bool? f=openFile.ShowDialog();
             if (f!=null && f.Value)
            {
                this.srcFile.Text = openFile.FileName;
            }
        }


        private void Button2_Click(object sender, RoutedEventArgs e)
        {
             ///设定目标文件全路径
              SaveFileDialog saveFile = new SaveFileDialog();
              saveFile.AddExtension = true;
              saveFile.Filter = "*.rar|*.rar|all files|*.*";
              saveFile.FilterIndex = 0;
              
              bool? f= saveFile.ShowDialog();
              if (f != null && f.Value)
              {
                  this.saveFilePath.Text = saveFile.FileName;
              }
        }


        private void Button3_Click(object sender, RoutedEventArgs e)
        {
            timeThread.Start();
        }


        private void Button4_Click(object sender, RoutedEventArgs e)
        {
            string fileName=this.srcFile.Text.Trim();
            string destPath=this.saveFilePath.Text.Trim();
            if(!File.Exists(fileName))
             {
                 MessageBox.Show("源文件不存在");
                 return;
             }
 
             ///copy file and nodify ui that rate of progress of file copy          
             this.copyFlag.Text = "开始复制。。。";


            //设置进度条最大值,这句代码写的有点郁闷
             this.copyProgress.Maximum = (new FileInfo(fileName)).Length;


             //保存复制文件信息,以进行传递
             CopyFileInfo c = new CopyFileInfo() { SourcePath = fileName, DestPath = destPath };
            //线程异步调用复制文件
             copyThread = new System.Threading.Thread(new ParameterizedThreadStart(CopyFile));           
             copyThread.Start(c);
 
             this.copyFlag.Text = "复制完成。。。";
             
            
        }




        /// <summary>
         /// 复制文件的委托方法
         /// </summary>
         /// <param name="obj">复制文件的信息</param>
         private void CopyFile(object obj)
         {
            CopyFileInfo c = obj as CopyFileInfo;
            CopyFile(c.SourcePath, c.DestPath);
         }


        /// <summary>
        /// 复制文件
         /// </summary>
         /// <param name="sourcePath"></param>
         /// <param name="destPath"></param>
         private void CopyFile( string sourcePath,string destPath)
         {
             FileInfo f = new FileInfo(sourcePath);
             FileStream fsR = f.OpenRead();
             FileStream fsW = File.Create(destPath);
             long fileLength = f.Length;
             byte[] buffer = new byte[1024];
             int n = 0;
             
             while (true)
             {
                 ///设定线程优先级
                 ///异步调用UpdateCopyProgress方法
                 ///并传递2个long类型参数fileLength 与 fsR.Position
                 this.displayCopyInfo.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new Action<long, long>(UpdateCopyProgress), fileLength, fsR.Position);
                 
                 //读写文件
                 n=fsR.Read(buffer, 0, 1024); 
                 if (n==0)
                 {
                     break;
                 }
                 fsW.Write(buffer, 0, n);
                 fsW.Flush();
                 System.Threading.Thread.Sleep(1);
             }
             fsR.Close();
             fsW.Close(); 
         }


         private void UpdateCopyProgress(long fileLength,long currentLength)
         {
             this.displayCopyInfo.Text = string.Format("总大小:{0},已复制:{1}", fileLength, currentLength);
             //刷新进度条            
             this.copyProgress.Value = currentLength;
         }


        public class CopyFileInfo
     {
         public string SourcePath { get; set; }
         public string DestPath { get; set; }        
     }


    }

}

---------------------------------------------------------------------------------------------------------xaml-----------------------------------------------------------------------------------------------------------------------

<Window x:Class="ThreadTest.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" Closed="Window_Closed">
    <Grid Height="186">        
        <Grid.ColumnDefinitions>


            <ColumnDefinition Width="132*" />
            <ColumnDefinition Width="236*" />
            <ColumnDefinition Width="147*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>
        <TextBlock Name="TextBlock1" Text="当前时间" Margin="35 10" Height="auto" Width="auto" />
        <TextBox Grid.Column="1" Name="displaytimebythread" Height="auto" Margin="0 10" />
        <TextBlock Grid.Row="1" Name="TextBlock2" Margin="35 10 0 10 " Text="源文件位置" />
        <TextBox Grid.Column="1" Grid.Row="1" Name="srcFile" Margin="0 10" />
        <TextBox Grid.Column="1" Grid.Row="2" Name="saveFilePath" Margin="0 10" />
        <TextBlock Grid.Row="2" Name="TextBlock3" Text="目标文件位置" Margin="35 10 0 10" />
        <Button Content="..." Grid.Column="2" Grid.Row="1" Name="Button1" Margin="10,10,66,10" Click="Button1_Click" />
        <Button Content="..." Grid.Column="2" Grid.Row="2" Name="Button2" Margin="10,10,66,10" Height="23" Click="Button2_Click"/>
        <Button Content="开始时间线程" Grid.Column="2" Name="Button3"  Margin="10,10,35,10" Height="23" Click="Button3_Click" />
        <Button Content="开始文件copy线程" Grid.Column="2" Grid.Row="3" Height="29" HorizontalAlignment="left" Name="Button4" VerticalAlignment="top" Width="119" Click="Button4_Click" />
        <TextBlock Grid.Row="3" Name="copyFlag" Text="开始复制" />
        <TextBlock Name="displayCopyInfo" Text="文件copy进行中" Grid.Row="3" Grid.Column="1"  />
        <ProgressBar Grid.Column="1" Grid.Row="4" Margin="0 2" Height="8" Name="copyProgress" />
    </Grid>
</Window>

0 0
原创粉丝点击