WPF多线程的实现

微软对WPF线程的描述如下:

 

Typically, WPF applications start with two threads: one for handling rendering and another for managing the UI. The rendering thread effectively runs hidden in the background while the UI thread receives input, handles events, paints the screen, and runs application code. Most applications use a single UI thread, although in some situations it is best to use several.

WPF应用程序都至少有两个线程,一个用于UI绘制,隐藏于后台,另一个用于管理UI,包括用响应用户输入执行后台代码等。

 

 

using System;
using System.Windows;
using System.ComponentModel;

 

BackgroundWorker worker;
ProgressDialog pd;

 

...

//需要定义一个BackgroundWorker

 private void btnDispacther_Click(object sender, RoutedEventArgs e)
        {
            int maxRecords = 1000;

            pd = new ProgressDialog();
            pd.Cancel += CancelProcess;

            System.Windows.Threading.Dispatcher pdDispatcher = pd.Dispatcher;

            worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;

            worker.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                for (int x = 1; x < maxRecords; x++)
                {
                    if (worker.CancellationPending)
                    {
                        args.Cancel = true;
                        return;
                    }

                    System.Threading.Thread.Sleep(10);

                    UpdateProgressDelegate update = new UpdateProgressDelegate(UpdateProgressText);
                    pdDispatcher.BeginInvoke(update, Convert.ToInt32(((decimal)x / (decimal)maxRecords) * 100), maxRecords);
                }
            };

            worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
            {
                pd.Close();
            };

            worker.RunWorkerAsync();
            pd.ShowDialog();
        }

 

 public delegate void UpdateProgressDelegate(int percentage, int recordCount);

 

        public void UpdateProgressText(int percentage, int recordCount)
        {
            pd.ProgressText = string.Format("{0}% of {1} Records", percentage.ToString(), recordCount);
            pd.ProgressValue = percentage;
        }

 

        void CancelProcess(object sender, EventArgs e)
        {
            worker.CancelAsync();
        }

 

源码下载:

http://www.dengfeng.org/soft/multithreading.zip

 

你可能感兴趣的:(thread,多线程,UI,object,application,WPF)