C# Background Thread

Keywords: Programming

This chapter describes: background threads
1. After the Initialize Component ();), the window pops up in the main interface, then blocks the execution of other threads, and then executes all the events of the form, then ends and closes the window. The main program continues to execute the interface display and closes after the execution is completed.
2. Using Loaded events, binding background threads in the target interface Window_Loaded, and defining public static AutoResetEvent myResetEvent = new AutoResetEvent(false) in the calling interface function.
Call OperationSettingConnectViewModel.myResetEvent.Set() in the background thread CompletedWork;
After the show, call myResetEvent.WaitOne(100);

public partial class MainWindow : Window
{

	private BackgroundWorker m_BackgroundWorker;// Statement of Background Objects

	public MainWindow()
	{
		InitializeComponent();

		m_BackgroundWorker = new BackgroundWorker(); // Instantiate background objects

		m_BackgroundWorker.WorkerReportsProgress = true; // Settings to notify progress
		m_BackgroundWorker.WorkerSupportsCancellation = true; // Settings can be cancelled

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

		m_BackgroundWorker.RunWorkerAsync(this);	//Execution thread
	}


	void DoWork(object sender, DoWorkEventArgs e)		//Main Code Event Processing
	{
		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)	//Update Notification Interface Update
	{
		int progress = e.ProgressPercentage;

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


	void CompletedWork(object sender, RunWorkerCompletedEventArgs e)	//Complete processing display
	{
		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();
	}
}

 

Posted by cdherold on Thu, 24 Jan 2019 07:39:15 -0800