简体   繁体   中英

Parallel.ForEach and ActiveX

I have a little problem with a Parallel.Foreach: I have a abstract class and a few derived classes. One of them calls an ActiveX-element (webbrowser). I want to make this object threadsafe, but it won't work:

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);
    }
}

SetApartmentState works only before thread is started.

You can't change MTA to STA on already running thread (which is clearly true for CurrentThread ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM