C#InvalidOperationException异常和跨线运行异常、InvalidOperationException

2023-09-07 00:57:49 作者:◆◇丶雪小染

在我的Windows窗体我有一个文本框和一个按钮,文本框tb_LogBox是多行文本框,我想创建一个后台工作是应该调用的函数,即LogTimer.DnT()时,我被编译并运行Visual Studio中抛出InvalidOperationException异常。

实际的错误,我越来越 跨线程操作无效:控制'tb_LogBox'从一个线程比它创建于其他线程访问。下面的示例code说明了什么,我试图做

 私人无效的button1_Click(对象发件人,EventArgs的)
{
    尝试
    {
    VAR体重=新的BackgroundWorker();
        bw.DoWork + = ExecuteOperations;
        bw.RunWorkerAsync();
    }
    赶上(例外前)
    {
        tb_LogBox.AppendText(Environment.NewLine += @ =+ ex.Message ++ ex.Source);
    }
}

私人无效ExecuteOperations(对象发件人,DoWorkEventArgs E)
{
    VAR FuncCall =新LogTimer();
    tb_LogBox.AppendText(Environment.NewLine + FuncCall.DnT()); //行我得到的错误。上
}

公共类LogTimer
{
    公共字符串DNT()
    {
    常量字符串datePat = @D / MM / YYYY;
    变种日期时间= DateTime.Now();
    返回则DateTime.ToString(da​​tePat);
    }
}
 

解决方案

尝试使用开始invoke方法:

 的BeginInvoke(新动作(()=>
    {
       tb_LogBox.AppendText(Environment.NewLine + FuncCall.DnT());
    }));
 
如何解决这个异常

这会比调用顺畅。

In my windows form I have a text box and a button, the text box "tb_LogBox" is multiline text box I am trying to create a background worker that is supposed to call a function i.e. "LogTimer.DnT()" when I compile is and run it Visual studio throws InvalidOperationException.

The actual Error I am getting Cross-thread operation not valid: Control 'tb_LogBox' accessed from a thread other than the thread it was created on. The following sample code illustrate what I am trying to do

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 + " =@= " + 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);
    }
}

解决方案

Try to use the begin invoke method :

    BeginInvoke(new Action(() =>
    {
       tb_LogBox.AppendText(Environment.NewLine + FuncCall.DnT());
    }));

This would be smoother than Invoke.