I am utilizing WebBrowser in multiple threads, however, after some executions (from 50 to 10000+) I get Access Violation Exception.
The related parts of the code:
Starting thread:
var thread = new Thread(() =>
{
ProcessingThread();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Processing Thread:
void ProcessingThread()
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.ScriptErrorsSuppressed = true;
while (!Shutdown)
{
string htmlstring = GetHTMLString();
webBrowser.DocumentText = htmlstring;
webBrowser.Document.OpenNew(true);
webBrowser.Document.Write(htmlstring);
webBrowser.Refresh();
HtmlDocument doc = webBrowser.Document;
//Do Work
}
}
There are usually from 2 to 8 such threads running at the same time.
I constantly get Access Violation on
webBrowser.Document.OpenNew(true);
I have read many similar questions but could not find the solution to the issue of mine.
I want to figure out what is the cause and the solution for the exception.
As of now, I am using WinForms and Visual Studio 2015 Update 3.
Exception string:
Exception thrown: 'System.AccessViolationException' in System.Windows.Forms.dll
Other thing I noted is that the higher version of .NET I use the less times the thread above manages to execute before throwing the exception.
For example, from ten times I have tried running it, it executes from 1000 to 10000 (absolute maximum of all tests I made, usually the maximum is around 5000) times on .NET 4.5 and from 70 to 1500 times on .NET 4.6.1.
I have tried:
- Using native code debugging option, but it still refers to the same line.
- Changing Platform Target without any noticeable result. Currently, it is x86.
- Turning code optimizations on and off.
- Running without debugger.
- Changing target framework to no result. Currently, it is .NET 4.5.2.
- Running/Debugging application on another machine.
I also know about WebRequest, WebClient and additionaly about HMTLAgilityPack, but I am using WebBrowser for its Javascript support.