猿问

如何使用另一个方法的参数为一个方法创建线程

我不能为这个方法创建一个线程,因为它只有一个参数。我看到了类似的问题,但我的方法是“分离的”,如果我将变量传递给它,错误表明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");

    }

}


aluckdog
浏览 133回答 1
1回答

蝴蝶刀刀

该方法必须匹配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...}
随时随地看视频慕课网APP
我要回答