在我的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);
}
}