Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
hi friends:

recently, I am writing a multi-thread program. but I meet a hard question for me. I used multi-thread to get web information. but, the main program halts when I click Cancel button.
Code is below:

<pre lang="cs">private void Cancel_bt_Click(object sender, EventArgs e)
{
       //currntThreaArray is a array including all of threads
    if (this.currntThreaArray != null && this.currntThreaArray.Length > 0)
    {
        new Thread(new ThreadStart(() =>
        {
            foreach (Thread t in this.currntThreaArray)
            {
                t.Abort();
                // t.Join(30000);
            }

            this.JudgeIfThreadCanceled();

        })).Start();
    }
}


C#
public void JudgeIfThreadCanceled()
        {
            do
            {
                bool ifAllCancel = true;

                foreach (Thread t in this.currntThreaArray)
                {
                    if ((t.ThreadState != ThreadState.AbortRequested) || (t.ThreadState != (ThreadState.WaitSleepJoin | ThreadState.AbortRequested)))
                    {
                        ifAllCancel = false;
                        break;
                    }
                }

                if (ifAllCancel)
                {
                    this.WebLog_RB.Invoke((MethodInvoker)delegate()
                    {
                   this.WebLog_RB.AppendText("--- Cancel all thread !!! --\r\n");
                    });
                }

                Thread.Sleep(1000);

            } while (true);
        }



C#
public void Start(out Thread[] threadArray)
  {
      counter = 0;
      rowNumber = 0;

      // Use multi-thread to get web information
      // The firstly: Create a thread array
      threadArray = new Thread[this.threadNum];

      // The second: Assign value to Thread Array
      for (int i = 0; i < threadArray.Length; i++)
      {
          threadArray[i] = new Thread(new ThreadStart(this.GetACompany));
          threadArray[i].Name = "Thread" + i;
          threadArray[i].IsBackground = true;

          // false stand for current thread no end
          // threadArrayState is a collection to record thread is running or end
          this.threadArrayState.Add(threadArray[i].Name, false);
      }

      // The third: Begin to perform multi-thread
      for (int j = 0; j < threadArray.Length; j++)
      {
          threadArray[j].Start();
      }
  }
Posted

1 solution

Try BackgroundWorker that provides an opportunity to cancel the operation without halting or freezing the application. Thread.Abort() is not a recommended way to abort the thread as it throws an ThreadAbortedException which might leave the application in unstable state. A graceful exit of a thread is done through a flag which should be polled continuously for exiting the thread.
http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.backgroundworker[^]
BackgroundWorker Class Sample for Beginners[^]
Thread vs. BackgroundWorker[^]
 
Share this answer
 
v2
Comments
Aaron Bo 18-May-14 3:46am    
Hi friend:
I have a question for BackgroundWorker class. Can it cancel or kill a running thread? By your prompt, I know that it can resolve the UI halt, but, I am not sure that it if can cancel a thread. I think the perfect resolution problem, not only resolve UI halt, but also should cancel the background threads!


Thanks!
Praveen Raghuvanshi 21-May-14 13:56pm    
Hi,
Recently, I also landed up with the similar situation wherein I have to Cancel the long-running task. I was implementing a progress dialog and used the link http://www.parago.de/2011/04/how-to-implement-a-modern-progress-dialog-for-wpf-applications/ for implementation. BackgroundWorker only provides a CancelAsync() which gets called once user cancels the operation after the completion of the task. It doesn't cancel the operation immediately. In order to cancel the operation immediately, I have to set the Completed event in the Cancel callback using RunWorkerCompletedEventArgs. Thread.Abort() is not a safe way. I wish you will find a better way to handle this scenario.
Aaron Bo 21-May-14 22:32pm    
No matter how, thanks!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900