1. 程式人生 > >C# 背景執行緒

C# 背景執行緒

本章講述:背景執行緒
1 在介面初始化(InitializeComponent();)後 設定 在主介面彈出該視窗,然後阻塞其他執行緒執行,然後執行本窗體所有的事件,之後結束、關閉視窗,主程式繼續執行 介面顯示,並且等待執行完成後關閉
2 使用Loaded事件,繫結目標介面  Window_Loaded中定義背景執行緒等   在呼叫介面函式中 定義public static AutoResetEvent myResetEvent = new AutoResetEvent(false);
在背景執行緒CompletedWork 呼叫OperationSettingConnectViewModel.myResetEvent.Set();
介面show出後, 呼叫myResetEvent.WaitOne(100);

public partial class MainWindow : Window
{

	private BackgroundWorker m_BackgroundWorker;// 申明後臺物件

	public MainWindow()
	{
		InitializeComponent();

		m_BackgroundWorker = new BackgroundWorker(); // 例項化後臺物件

		m_BackgroundWorker.WorkerReportsProgress = true; // 設定可以通告進度
		m_BackgroundWorker.WorkerSupportsCancellation = true; // 設定可以取消

		m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
		m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
		m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);

		m_BackgroundWorker.RunWorkerAsync(this);	//執行執行緒
	}


	void DoWork(object sender, DoWorkEventArgs e)		//主程式碼事件處理
	{
		BackgroundWorker bw = sender as BackgroundWorker;
		MainWindow win = e.Argument as MainWindow;

		int i = 0;
		while ( i <= 100 )
		{
			if (bw.CancellationPending)
			{
				e.Cancel = true;
				break;
			}

			bw.ReportProgress(i++);
 
			Thread.Sleep(1000);

		}
	}

	void UpdateProgress(object sender, ProgressChangedEventArgs e)	//更新 通知介面更新
	{
		int progress = e.ProgressPercentage;

		label1.Content = string.Format("{0}",progress);
	}


	void CompletedWork(object sender, RunWorkerCompletedEventArgs e)	//完成處理顯示
	{
		if ( e.Error != null)
		{
			MessageBox.Show("Error");
		}
		else if (e.Cancelled)
		{
			MessageBox.Show("Canceled");
		}
		else
		{
			MessageBox.Show("Completed");
		}
	}


	private void button1_Click(object sender, RoutedEventArgs e)
	{
		m_BackgroundWorker.CancelAsync();
	}
}