从其他线程读取值。

时间:2011-04-24 01:42:13

标签: c# .net multithreading

我创建了一个帖子。 如何从GUI线程中读取变量值?

我知道如何改变它们。我不知道如何阅读它们。

这就是我用来改变GUI线程的东西:

    public void Log(string message)
    {
        MethodInvoker m = () => { Log_textBox.Text += message; };
        if (InvokeRequired)
        {
            BeginInvoke(m);
        }
        else
        {
            Invoke(m);
        }
    }

我需要从GUI线程中读取一些值:

    public void StartBot()
    {
        Klient.StartBot(selectedType, (int)nb_count.Value, nb_nonstop.Checked, (...)int.Parse(extra_set.SelectedItem.ToString()));
    }

    private void StartStopButton_Click(object sender, EventArgs e)
    {
            Thread questThread = new Thread(StartBot);
            Klient.RequestToStop = false;
            questThread.Start();
    }

我在Klient.StartBot(...)参数列表中遇到了交叉线程操作错误。

如何解决?

1 个答案:

答案 0 :(得分:2)

您可以通过创建Func<ReturnType>从已调用的委托中返回值 Invoke将返回函数的返回值。

或者,您可以在委托中设置局部变量并使用Invoke(而不是BeginInvoke)来调用它,因为这不会等待它完成)