在我的Windows窗体中我有一个文本框和一个按钮,文本框“tb_LogBox”是多行文本框我试图创建一个应该调用一个函数的后台工作, LogTimer.DnT()“当我编译时,并运行它Visual Studio中抛出InvalidOperationException。C#InvalidOperationException和跨线程操作
实际发生的错误 跨线程操作无效:从其创建的线程以外的线程访问控制'tb_LogBox'。下面的代码示例说明了什么,我试图做
private void button1_Click(object sender, EventArgs e)
{
try
{
var bw = new BackgroundWorker();
bw.DoWork += ExecuteOperations ;
bw.RunWorkerAsync();
}
catch (Exception ex)
{
tb_LogBox.AppendText(Environment.NewLine + " [email protected]= " + ex.Message+" "+ex.Source);
}
}
private void ExecuteOperations(object sender, DoWorkEventArgs e)
{
var FuncCall = new LogTimer();
tb_LogBox.AppendText(Environment.NewLine + FuncCall.DnT()); // the line i am getting the error. on
}
public class LogTimer
{
public string DnT()
{
const string datePat = @"d/MM/yyyy";
var dateTime = DateTime.Now();
return dateTime.ToString(datePat);
}
}