看下面的代码:

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.ForEach中使用了try,但由于并行更改,我无法控制MyMethod中的全局变量。

最佳答案

您可以在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);
     }
}

关于c# - 如何传递值以从外部try/catch捕获块(不使用全局变量),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12874217/

10-09 18:27