1. 程式人生 > >Csharp中Thread的四種建構函式

Csharp中Thread的四種建構函式

  • 帶引數的建構函式

第一種:Thread(ParameterizedThreadStart)

 private void treeView1_NodeMouseClick()
        {
            try
            {
                TreeNode tn = new TreeNode();
                tn = e.Node;

                Thread th = new Thread(new ParameterizedThreadStart(URLshow));
                th.IsBackground = true
; th.Start(tn); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } } private void URLshow(object tn) { try { TreeNode tnn = (TreeNode)tn; this.Invoke(new EventHandler(delegate
{ this.textBox3.Text = FTPIP + tnn.FullPath.ToString().Replace("\\", "/"); })); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }

第二種:Thread(ParameterizedThreadStart, Int32)

  • 不帶引數的建構函式

    第三種:Thread(ThreadStart)

private void treeView1_NodeMouseClick()
        {
            try
            {
                TreeNode tn = new TreeNode();
                tn = e.Node;

                Thread th = new Thread(new ParameterizedThreadStart(URLshow));
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }

        private void URLshow()
        {
            try
            {
                this.Invoke(new EventHandler(delegate
                    {
                            this.textBox3.Text = FTPIP + tnn.FullPath.ToString().Replace("\\", "/");
                    }));
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }

第四種:Thread(ThreadStart, Int32)

總結:
第二種和第四種的程式碼流程跟第一種和第三種相似,區別在於就多一個引數,該引數代表著執行緒要使用的最大堆疊大小(以位元組為單位);

溫馨提示:避免使用此建構函式過載。 使用的預設堆疊大小Thread(ParameterizedThreadStart)建構函式過載是執行緒的建議的堆疊大小。 如果一個執行緒出現記憶體問題,最可能的原因程式設計錯誤,例如無限遞迴。

外附加一種

 private void treeView1_NodeMouseClick()
        {
            try
            {
                TreeNode tn = new TreeNode();
                tn = e.Node;

                Thread th = new Thread(new ThreadStart(delegate
                    {
                        URLshow(tn);
                    }));
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }

        private void URLshow(object tn)
        {
            try
            {
                TreeNode tnn = (TreeNode)tn;
                this.Invoke(new EventHandler(delegate
                    {

                        this.textBox3.Text = FTPIP + tnn.FullPath.ToString().Replace("\\", "/");

                    }));
            }
            catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); }
        }