1

看看下面的代码:

try
{
    Parallel.Foreach(...)//50 Thread For Each Time
    {
        string str = MyMethod();
    }
}
catch
{

}
public string MyMethod()
{
     CookieContainer cookieJar = new CookieContainer();

     // Some code that throws an exception.
}

我怎样才能传递cookieJar到 catch 块?

注意:
由于某种原因,我不能使用全局变量。我正在使用Parallel.ForEachin并且由于并行更改try,我无法控制内部的全局变量。MyMethod

4

1 回答 1

4

您可以捕获异常MyMethod并重新抛出一个新的异常来保存该CookieContainer对象:

try
{
    Parallel.ForEach(...)
    {
        string str = MyMethod();
    }
}
catch (AggregateException ae)
{
    // This is where you can choose which exceptions to handle.
    foreach (var ex in ae.InnerExceptions.OfType<MyCookieException>())
    {
        CookieContainer c = ex.CookieContainer;

        // Do stuff with CookieContainer.
    }
}

public string MyMethod()
{
     CookieContainer cookieJar = new CookieContainer();
     try
     {
         // Some code that throws an exception
     }
     catch (Exception ex)
     {
         throw new MyCookieException(ex, cookieJar);
     }
}
于 2012-10-13T15:01:43.270 回答