如何为具有其他方法的参数的方法创建线程

时间:2019-06-30 14:16:18

标签: c#

我无法为此方法创建线程,因为它具有一个参数。我看到类似的问题,但是我的方法是“分开的”,如果我将变量传递给它,错误将指出在当前上下文中不存在名称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 个答案:

答案 0 :(得分:1)

PressBind方法必须与ParameterizedThreadStart的签名匹配,该签名接受类型为object的参数。在PressBind method内部,将此参数转换为字符串。该值将传递到Thread.Start中的线程。

还要注意,为了从另一个线程更新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...
}