Loading... 这个异常通常是由于在不同的线程中访问 UI 控件而引发的,因为 UI 控件是与创建它们的线程相关联的。 在 Windows Forms 中,只能从创建 UI 控件的线程(通常是主线程)访问和更新这些控件。如果你在其他线程中尝试访问或更新 UI 控件,就会抛出 `InvalidOperationException` 异常。 为了解决这个问题,你可以使用 `Control.Invoke` 或 `Control.BeginInvoke` 方法在 UI 线程上执行相应的操作。 以下是一个示例,展示了如何在其他线程中更新 UI 控件的文本框: ```csharp using System; using System.Threading; using System.Windows.Forms; public class Program { private static TextBox textBoxLog; public static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form form = new Form(); textBoxLog = new TextBox(); textBoxLog.Multiline = true; textBoxLog.Dock = DockStyle.Fill; form.Controls.Add(textBoxLog); Thread workerThread = new Thread(WorkerMethod); workerThread.Start(); Application.Run(form); } private static void WorkerMethod() { for (int i = 0; i < 5; i++) { string message = "Worker Thread: " + i; // 在 UI 线程上更新文本框 textBoxLog.Invoke((MethodInvoker)(() => { textBoxLog.AppendText(message + Environment.NewLine); })); Thread.Sleep(1000); } } } ``` 在上述示例中,我们创建了一个窗体和一个多行文本框 `textBoxLog`。然后,我们创建了一个工作线程 `workerThread`,在其中使用 `Invoke` 方法在 UI 线程上更新文本框的内容。 通过使用 `textBoxLog.Invoke` 方法,我们将 UI 操作封装在一个 `MethodInvoker` 委托中,并传递给 `Invoke` 方法。这样可以确保操作在 UI 线程上执行。 注意,在使用 `Invoke` 方法时,必须保证 UI 线程处于运行状态,否则可能会引发异常。因此,我们使用 `Application.Run(form)` 来启动应用程序的消息循环,确保 UI 线程一直处于运行状态。 ### 解决方法二:  ```csharp public Form1() { InitializeComponent(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false } ``` ```csharp System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false ``` 最后修改:2023 年 06 月 15 日 © 允许规范转载 打赏 赞赏作者 微信 赞 0 如果觉得我的文章对你有用,请随意赞赏