C#多线程形式的AccessViolationException [英] AccessViolationException in C# multithreaded form
问题描述
首先这是我的第一个 C# 项目.我已经在这个项目上工作了大约 6 个月.
First off this is my first C# project. I have been working on this project for about 6 months.
我们有一个 winforms 程序,它包含一个日志记录 GUI.为了让程序的其余部分保持响应,我想在一个单独的线程上创建日志 gui,因为当有很多事情发生时它可能会非常密集.
We have a winforms program and it contains a logging GUI. In order to keep the rest of the program responsive I wanted to create the logging gui on a separate thread since it can be quite intensive when lots of stuff is going on.
这就是我尝试在新的 GUI 线程上打开表单的方式.一般来说,它可以工作并保持主 gui 响应.然而,当它被激活时,我们现在随机得到一个 AccessViolationException (http://pastebin.com/7tLtBSei)不知所措.
This is how I attempted to open the the form on a new GUI thread. In general it works and keeps the main gui responsive. However we now randomly get a AccessViolationException (http://pastebin.com/7tLtBSei) when this is activated and I am at a loss.
var thread = new Thread(() =>
{
loggingForm = new LoggingForm(Logger.path);
Application.Run(loggingForm);
});
thread.Name = "LoggingFormGUIThread";
thread.Start();
日志 GUI 只是批量读取日志文件并将其附加到 RichTextBox.它不涉及任何托管代码.
The logging GUI just batch reads the log file and appends it to a RichTextBox. It doesn't touch any managed code.
推荐答案
需要将线程的单元状态设置为STA.
You need to set the apartment state of the thread to STA.
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "LoggingFormGUIThread";
thread.Start();
这是许多用户界面组件(例如 RichTextBox
)正常运行所必需的.
This is required for many user interface components (such as RichTextBox
) to function correctly.
这篇关于C#多线程形式的AccessViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!