【问题标题】:Parallel.ForEach and ActiveXParallel.ForEach 和 ActiveX
【发布时间】:2012-12-11 23:17:26
【问题描述】:

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

【问题讨论】:

    标签: c# multithreading user-interface activexobject


    【解决方案1】:

    SetApartmentState 仅在线程启动之前工作。

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

    【讨论】:

    • 那么有机会处理这种情况吗?还是我必须用 ActiveX 提取零件并自行处理?
    【解决方案2】:

    我认为您可能需要做一些事情来启动新线程来完成工作。您可能还必须为每个线程创建单独的 Web 浏览器。对于一个网络浏览器来说,这可能有点麻烦。您可以考虑使用 WebClient 或其他方式来发出 Web 请求。

    【讨论】:

      猜你喜欢
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2011-06-11
      相关资源
      最近更新 更多