Reputation: 11
I have a Windows Form. When clicking on "Ok" some Work will be done which takes some time. During the process all controls of the form got disabled so the user cannot do something. Except one button, abort. This button shall be still available to abort the process task. I start a new Thread, fine. The problem is that when clicking ob abort the event is called after the thread finished.
Heres he code to start the thread (within my buttonOk_Click Eventmethod) (I am using the priority to pretend the thread of beeing aborted while I am doing some database actions):
t1 = new System.Threading.Thread(processing);
t1.Priority = System.Threading.ThreadPriority.Normal;
t1.Start();
Heres the code where I catche the abort event but which is not accessed during the thread is working. (Withing ButtonAbort_Click-Method)
while (t1.Priority == System.Threading.ThreadPriority.Highest)
{
System.Threading.Thread.Sleep(1000);
}
try
{
lock (t1)
{
if (t1.ThreadState != System.Threading.ThreadState.Aborted)
{
//abort Thread
t1.Abort();
//wait that lock is not released to early
while (t1.ThreadState != System.Threading.ThreadState.Aborted) { }
}
}
}
Hope you can help me. Thanks.
Upvotes: 1
Views: 1422
Reputation: 48949
Your ButtonAbort_Click
event handler is spinning around in circles tieing up the UI thread. That is why your form "seems not to run as own thread". What you need to do have your processing
method periodically poll for a signal to gracefully terminate. Aborting threads is not a good idea. Here is what your code should look like.
class YourForm : Form
{
private ManualResetEvent terminate = new ManualResetEvent(false);
private void YourThread()
{
while (!terminate.WaitOne(0))
{
// Do some more work here.
}
}
private void ButtonAbort_Click(object sender, EventArgs args)
{
terminate.Set();
}
}
Notice that the thread is calling ManualResetEvent.WaitOne
on each iteration of the loop to test to see if the terminate signal is set.
Upvotes: 1