我想将文本写入文本框。为了能够从不同的线程做到这一点,我调用了一个静态方法,它调用一个持有调用和文本框写入的非静态方法。当这样做。我得到的错误,它不能调用,直到设置了窗口句柄,所以我设置它。我的问题是,是的调用循环/崩溃
if (!this.IsHandleCreated)
this.CreateHandle();
下面
在代码中的位置是唯一的一个,我的程序不会崩溃,但现在它的循环(indefinetly)只有BeginInvoke的代码,但实际上不是文本设置代码如下。我究竟做错了什么?
代码:
private void ActualLog(string input)
{
var currentForm = form as Main;
if (!this.IsHandleCreated)
this.CreateHandle();
if (currentForm.txtServerLog.InvokeRequired)
{
this.BeginInvoke(new Action<string>(ActualLog), new object[] { input });
return;
}
else
{
currentForm.txtServerLog.Text += input + "\r\n";
currentForm.txtServerLog.Refresh();
}
}
public static void Log(string input)
{
Main main = new Main();
main.ActualLog(input);
}
从我的线程,我会叫Log("Any String");
@JanH。我不是100%确定你想要做什么,但我已经在上面添加了一个样本。 – furkle 2014-11-01 18:16:14
谢谢!在你的例子中,当使用Invoke而不是BeginInvoke时,它起作用。具有这两个函数的东西只是让我可以从annother Thread中调用Log(),因为Invoke在静态函数中是不允许的(所以我只是把它放在非静态函数中,并从静态函数中调用它)。不过谢谢:) – 2014-11-01 19:44:10
@JanH。啊,我花了更多的时间在WPF上比WinForms,所以我对Invoke/BeginInvoke的区别有点生疏。很高兴听到它的帮助! – furkle 2014-11-01 19:45:08