Create a thread as if it were a split application in C #

I had a bunch of exceptions when trying to use WebBrowserin a multi-threaded application. COM component, protected memory and other exceptions in everything that I do with WebBrowser. I just gave up and returned to my single thread version, which works great. I would post the code, but it's hard to localize the cause of the problem when I get exceptions in many places. Thus, if it works fine as an application with one thread, and if it also works fine when running multiple instances of the same application, there should be a way to simulate several applications running from the same application, without actually creating a separate application that I will work from the main application. My question is: how do I get Windows to process my threads as if they were different instances? This should fix the problem, because, as I said,when I have different instances, I get no exceptions. I hope I will be clear enough.

+2
source share
3 answers

I think your problem may have something to do with how Microsoft.NET handles user interface elements. Basically, any control method should be called from the thread that created it (possibly even the main user interface thread). Otherwise, you will get a bunch of access-related exceptions. I believe that you will need to use the InvokeRequired and Invoke properties to call into the control, which also means that you will need to define a delgate function that wraps each method that you want to call. Using the WebBroweser.Url property as an example, you can write something like this:

public delegate void SetWebAddressDelegate ( WebBrowser browser, Uri newUrl);

public void SetWebAddress ( WebBrowser browser, Uri newUrl )
{
    if (browser.InvokeRequired)
        browser.Invoke(new SetWebAddressDelegate(SetWebAddress), browser, newUrl);
    else
        browser.Url = newUrl;
}
+1

WebBrowser - COM- Internet Explorer. COM-, " ". , . : STA, .

, , Windows Forms:

    private void runBrowserThread(Uri url) {
        var th = new Thread(() => {
            var br = new WebBrowser();
            br.DocumentCompleted += browser_DocumentCompleted;
            br.Navigate(url);
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
        var br = sender as WebBrowser;
        if (br.Url == e.Url) {
            Console.WriteLine("Natigated to {0}", e.Url);
            Application.ExitThread();
        }
    }

, DocumentCompleted . , .

+2

It looks like you can share one instance of WebBrowser by stream. If each thread has its own instance and the threads do not interact with each other, I expect this to be equivalent to starting multiple process instances.

0
source

All Articles