+ -
当前位置:首页 → 问答吧 → 多线程中,怎样在一个线程结束的时候,触发某一个操作。。

多线程中,怎样在一个线程结束的时候,触发某一个操作。。

时间:2011-12-19

来源:互联网

各位大侠。

小弟到现在为止,基本没弄过多线程的。

所以,一时接触到这样的问题,也是一头雾水。。

多线程中,怎样在一个线程结束的时候,触发某一个操作。

下面是我的代码,请指教。。

C# code

private void btnStart_Click(object sender, EventArgs e)
        {

            int iThreadCount = Convert.ToInt32(txtThreadCount.Text);

            ArrayList aList = new ArrayList();

            for (int i = 0; i < iThreadCount; i++)
            {
                Thread scoreThread = new Thread(new ThreadStart(Execute));
                scoreThread.Start();
                scoreThread.Name = "线程" + i.ToString();
                
                //MessageBox.Show(scoreThread.ThreadState.ToString());
            }
        }



        private void Execute()
        {
            string strSalesOrderName = txtSalesOrderName.Text;

            Score.Score _score = new Score.Score();
            _score.QueryTest(strSalesOrderName);
        }




怎样在一个线程结束的时候,往aList里面添加这个线程的完成状态。。

作者: zhuoweizhao   发布时间: 2011-12-19

有人吗?

作者: zhuoweizhao   发布时间: 2011-12-19

在Execute方法最后直接操作aList就可以了,

  private void Execute()
  {
  string strSalesOrderName = txtSalesOrderName.Text;

  Score.Score _score = new Score.Score();
  _score.QueryTest(strSalesOrderName);

  lock(aList)
  {
  aList.AddLast(xxx);
  }
  }

作者: stonespace   发布时间: 2011-12-19

操作aList的时候,最好用lock把它锁住,

作者: stonespace   发布时间: 2011-12-19

你是说ManualResetEvent?

作者: ssp2009   发布时间: 2011-12-19

感谢你的回复。

我想,我应该这样描述吧:

假如我同时开启1000个线程,怎样在当这1000个线程里面的每一线程状态完成的时候,就往一个textbox输出线程的完成信息。

作者: zhuoweizhao   发布时间: 2011-12-19

引用 2 楼 stonespace 的回复:

在Execute方法最后直接操作aList就可以了,

private void Execute()
{
string strSalesOrderName = txtSalesOrderName.Text;

Score.Score _score = new Score.Score();
……


感谢你的回复。

我想,我应该这样描述吧:

假如我同时开启1000个线程,怎样在当这1000个线程里面的每一线程状态完成的时候,就往一个textbox输出线程的完成信息。

作者: zhuoweizhao   发布时间: 2011-12-19

引用 4 楼 ssp2009 的回复:

你是说ManualResetEvent?


虽然我对这个不熟,但应该不是这个才对。

作者: zhuoweizhao   发布时间: 2011-12-19

你可以直接操作textbox,但不能直接更改textbox的方法和属性,必须要用Invoke来更改,

public delegate void AppendTextProc(string strText);

private void AppendThreadInfo(string strText)
{
  if (textbox1.InvokeRequired)
  {
  AppendTextProc d = new AppendTextProc(AppendThreadInfo);
  textbox1.Invoke(d, new object[] { strText });
  }
  else
  {
  textbox1.Text += strText;
  }
}

  private void Execute()
  {
  string strSalesOrderName = txtSalesOrderName.Text;

  Score.Score _score = new Score.Score();
  _score.QueryTest(strSalesOrderName);

  //向textbox1输出信息,
  AppendThreadInfo("我已经执行完了");
}

引用 6 楼 zhuoweizhao 的回复:
引用 2 楼 stonespace 的回复:

在Execute方法最后直接操作aList就可以了,

private void Execute()
{
string strSalesOrderName = txtSalesOrderName.Text;

Score.Score _score = new Score.Score();
……


感谢你的回复。

我想,……

作者: stonespace   发布时间: 2011-12-19

相关阅读 更多

热门下载

更多