winform 線程中使用textbox

1)線程不帶參數

Thread objThread = new Thread(new ThreadStart(ExecuteSendConnectDevice));
objThread.IsBackground = true;
objThread.Start();

private void ExecuteSendConnectDevice() {
            Console.WriteLine("this is no param ExecuteSendConnectDevice");
        }

2)使用lambada

new Thread(new ThreadStart(() =>
            {
                while (sendFlag)
                {
                    serialSendMsg(connectBytes);
                    Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "發送:" + ByteCalculator.ByteToHexStr(connectBytes));
                    Thread.Sleep(1000);
                }

            })).Start();

3)線程帶參數  同時 在線程中展示textbox

ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ParamExecuteSendConnectDevice);
            Thread myThread = new Thread(ParStart);
            myThread.Start(connectBytes);

 

public void ParamExecuteSendConnectDevice( Object obj) {
            while (sendFlag) {
                byte[] connectBytes = (byte[])obj;
                serialSendMsg(connectBytes);
                txt_logSetText(ByteCalculator.ByteToHexStr(connectBytes));
                Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + "發送:" + ByteCalculator.ByteToHexStr(connectBytes));
                Thread.Sleep(1000);
            }            
        }

 

//注意這裏要使用委託,而且把委託放到一個正常的函數中

delegate void SetTextCallback(string text);
        private void txt_logSetText(string str)
        {

            if (this.txt_log.InvokeRequired)
            {

                SetTextCallback d = new SetTextCallback(txt_logSetText);
                this.Invoke(d, new object[] { str });
            }
            else
            {
                scrollTextBox(txt_log, str);
            }
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章