本文介绍了如何取消所有工作线程,并避免停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
    }
}







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);
        }










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();
      }
  }

推荐答案


这篇关于如何取消所有工作线程,并避免停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:20