Skip to content

Instantly share code, notes, and snippets.

@DamianSuess
Created October 22, 2016 20:26
Show Gist options
  • Save DamianSuess/d74ab5e6340d09e8981426271867741c to your computer and use it in GitHub Desktop.
Save DamianSuess/d74ab5e6340d09e8981426271867741c to your computer and use it in GitHub Desktop.
Thread Background Worker
namespace XI.Template
{
using System.ComponentModel;
class ThreadTest
{
#region Constructor and attributes
private System.ComponentModel.BackgroundWorker _thread;
/// <summary>Create our thread</summary>
public ThreadTest()
{
this._thread = new System.ComponentModel.BackgroundWorker()
{
WorkerSupportsCancellation = true
};
this._thread.DoWork += new System.ComponentModel.DoWorkEventHandler(this.ThreadTest_DoWork);
this._thread.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.ThreadTest_RunWorkerCompleted);
}
#endregion
#region Properties
/// <summary>Return if thread is currently running or not</summary>
public bool ThreadIsBusy { get { return this._thread.IsBusy; } }
#endregion
#region Public Methods
/// <summary>Start the main operation to find frozen applications.</summary>
/// <returns>True if started, False if already running</returns>
public bool StartThread()
{
if (this.ThreadIsBusy)
return false;
else
{
this._thread.RunWorkerAsync(); // Make the magic happen
return true;
}
}
/// <summary>Stop the operation</summary>
public void CancelThread()
{
this._thread.CancelAsync();
}
#endregion
#region Event Handlers
/// <summary>The main thread</summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ThreadTest_DoWork(object sender, DoWorkEventArgs e)
{
// Our thread operation
// Check to see if someone hit the cancel button
// Place this check throughout code
BackgroundWorker bgw = sender as BackgroundWorker;
if (bgw != null && bgw.CancellationPending)
{
e.Cancel = true;
return;
}
}
/// <summary>Thread has completed, send a signal back</summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ThreadTest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Did someone hit cancel?
if (e.Cancelled)
{
// Someone pressed, Cancel!
}
}
#endregion Event Handlers
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment