Skip to main content
 首页 » 编程设计

c#之如何从外部 try/catch 传递值到 catch block (不使用全局变量)

2024年02月20日12tintown

看看下面的代码:

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 block ?

注意:
出于某种原因,我不能使用全局变量。我在 try 中使用 Parallel.ForEach 并且由于并行更改,我无法控制 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); 
     } 
}