0

我对 Parallel.Foreach 有一点问题:我有一个抽象类和一些派生类。其中之一称为 ActiveX 元素(网络浏览器)。我想让这个对象线程安全,但它不起作用:

Parallel.ForEach(stringarray, currentfile =>
{
    // When we have something, set the thread to STA
    // So we can call a WebBrowser
    if (currentfile.Contains("something"))
        Thread.CurrentThread.SetApartmentState(ApartmentState.STA);

    // Here is the part where the WebBrowser is called
    // But it fails and the debugger says that
    // Thread.CurrentThread.ApartmentState is MTA, but the condition above
    // is true  
    obj track = IService.Create(currentfile);

    if (track != null)
    {
        lock(my_list)
            my_list.Add(track);
    }
}
4

2 回答 2

1

SetApartmentState线程启动之前起作用。

您不能在已经运行的线程上将 MTA 更改为 STA(这对于 显然是正确的CurrentThread)。

于 2012-12-11T23:21:59.223 回答
0

I think you'll probably have to do something where you spin up new threads to do the work. You will probably have to create individual web browsers for each thread also. This might get kind of hairy for just a web browser. You might consider WebClient or some other way to make web requests.

于 2012-12-11T23:41:01.890 回答