创建线程就像如果它是在C#中分离应用程序 [英] Create thread just like if it were a separated application in C#

查看:91
本文介绍了创建线程就像如果它是在C#中分离应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直有一帮异常试图用的 web浏览器在多线程应用程序。 COM组件,受保护的内存和其他异常,无论我做的东西与web浏览器。我只是放弃了,又回到其正常工作,我的单线程版本。我会后code,但很难本地化问题的原因,当我得到异常,在如此多的斑点。所以,如果作为一个单独的线程的应用程序运行良好,如果当我运行相同的应用程序也能正常工作的几个实例,应该有一种方法来模拟从一个单一的应用程序中运行多个应用程序,而无需实际做出分隔的应用我会从主应用程序运行。我的问题,那么,我该怎么使Windows把我的线,好像他们是不同的实例?这将消除这一问题,因为,正如我所说,当他们在不同情况下,我没有得到任何的异常。希望我是清楚不过了。

I've been having a bunch of exceptions when trying to use a WebBrowser on a multithread application. COM component, protected memory and other exceptions everywhere I do stuff with the WebBrowser. I just gave up and went back to my single thread version which works fine. I would post code but it's hard to localize the cause of the problem when I get exceptions at so many spots. So, if as a single thread application it runs fine, and if when I run several instances of the same application it also works fine, there should be a way to simulate several applications running from a single application without having to actually make a separated application that I would run from the main application. My question, then, is how can I make Windows treat my threads as if they were different instances? This should eliminate the problem, since, as I said, when they ARE different instances I don't get any exception. Hope I'm being clear enough.

推荐答案

我觉得你的问题可能有事情做与Microsoft.NET处理UI控件的方式。基本上,任何方法控制必须调用从创建它的线程(甚至在主UI线程专用)。否则,你会得到一堆访问相关的异常。我相信你会需要使用InvokeRequired属性和调用方法来调用到控制,这也意味着你必须定义一个delgate函数封装每个要调用的方法。使用WebBroweser.Url属性为例,你可以这样写:

I think your issue may have something to do with the way Microsoft.NET handles UI controls. Basically, any method for a control must be called from the thread that created it (perhaps even the main UI thread exclusively). Otherwise, you will get a bunch of access-related exceptions. I believe you will need to use the InvokeRequired property and Invoke method to call into the control, which also means that you will have to define a delgate function that wraps each method you want to call. Using the WebBroweser.Url property as an example, you could 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;
}

这篇关于创建线程就像如果它是在C#中分离应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆