I have to implement validation on datatable in my project but it should be running on different background thread, not main UI thread. And once it's done it should show list of errors on screen. This validation runs from differences different places, there are 6 to 7 places which might causes data table error. I have below function written which can be called from those 6 to 7 places to perform validation:
Thread validationThread = null;
public void RunDataTableValidation()
{
validationThread = new Thread(new ThreadStart(() => validationHandler()));
validationThread.Name = "DataGridValidationThread";
validationThread.IsBackground = true;
validationThread.Start();
}
}
public void validationHandler(Label FakeLabel)
{
try { //all validation code}
finally
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => ProcessingDone()));
}
}
void ProcessingDone()
{
if (validationThread != null && validationThread.ThreadState == ThreadState.Stopped)
{
validationThread.Abort();
}
}
My Issue is: Every time I abort thread when once it's done with it's work. But I also want to Abort thread if current thread is still running and some other code calls this function and start new thread. I know I can use ThreadPool but please help me - how I can implement thread pool in my above code? So it automatically kills all running thread in thread pool before it starts new thread
Edit:
public void RunDataTableValidation()
{
ThreadPool.QueueUserWorkItem(o =>
{
try
{
validationHandler();
}
catch (NotSupportedException) { }
});
}
public void validationHandler(Label FakeLabel)
{
try
{
foreach (DataRow drRow in this.CurrentDataTable.Rows)
{
}
Thread.Sleep(7000); ( i put sleep right now for testing becoz this code takes few secs becoz of 500+ rows of datagrid
}
finally
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => ProcessingDone()));
}
}