亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用另一個方法的參數為一個方法創建線程

如何使用另一個方法的參數為一個方法創建線程

C#
aluckdog 2023-05-14 16:46:45
我不能為這個方法創建一個線程,因為它只有一個參數。我看到了類似的問題,但我的方法是“分離的”,如果我將變量傳遞給它,錯誤表明text當前上下文中不存在該名稱(參數名稱)。private void Form1_Load(object sender, EventArgs e){    Thread TH = new Thread(PressBind); //I cant make thread for this method    TH.SetApartmentState(ApartmentState.STA);    CheckForIllegalCrossThreadCalls = false;    TH.Start();}private void TxBxKTB_TextChanged_1(object sender, EventArgs e){    TextBox objTextBox = (TextBox)sender;    string text = objTextBox.Text;    label2.Text = $"the bind key is {text}";    PressBind(text);}void PressBind(string text){    Enum.TryParse(text, out Key key1);    Thread.Sleep(40);    label1.Text = "ready";    if (Keyboard.IsKeyDown(key1))    {        Thread.Sleep(40);        SendKeys.SendWait("e");    }}
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

該方法必須匹配ParameterizedThreadStartPressBind的簽名,它接受 type 的參數。在 中,將此參數轉換為字符串。該值在Thread.Start中傳遞給線程。objectPressBind method

另請注意,為了Label從另一個線程更新文本,您必須使用Invoke。

private void Form1_Load(object sender, EventArgs e)

{

? ? Thread TH = new Thread(PressBind); //I cant make thread for this method

? ? TH.SetApartmentState(ApartmentState.STA);

? ? CheckForIllegalCrossThreadCalls = false;

? ? TH.Start("some-text" /* here you pass the text */);

}


private void TxBxKTB_TextChanged_1(object sender, EventArgs e)

{

? ? TextBox objTextBox = (TextBox)sender;

? ? string text = objTextBox.Text;

? ? label2.Text = $"the bind key is {text}";

? ? PressBind(text);

}


void PressBind(object state)

{

? ? string text = (string)state; // cast object parameter back to string


? ? // do other things...


? ? // must use InvokeRequired + Invoke if accessing Label?

? ? // created by the UI thread

? ? if (InvokeRequired)

? ? {? ??

? ? ? ?Invoke(() => label1.Text = "ready");?

? ? }

? ? else

? ? {

? ? ? ?label1.Text = "ready"; // we're on the UI thread

? ? }


? ? // do other things...

}


查看完整回答
反對 回復 2023-05-14
  • 1 回答
  • 0 關注
  • 166 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號