C# - 使用线程获取有问题的方法结果
本文关键字:有问题 方法 结果 获取 线程 | 更新日期: 2023-09-27 18:31:30
我有某种数据处理,它取决于返回处理中使用的结果的有问题方法的成功。
外部方法有问题,因为它运行缓慢,它可能会崩溃并抛出任何类型的异常,而且我没有它的源代码。
我想在处理开始时使用线程以节省一些时间,因为即使没有那个有问题的方法,我的处理也足够长。 但是有一点,我必须从有问题的方法中获得有效的结果,如果它失败,我就无法继续。
我希望在主线程中使用有问题的方法的异常,以便它们获得与我的处理可能引发的任何其他异常相同的异常处理。
这是我的代码 - 它看起来还可以并且有效,但对我来说看起来太麻烦了,所以我的问题:有没有更好的方法来正确管理线程对有问题方法的调用及其潜在的异常?
我的环境是 .NET 3.5,所以请我想获得针对该版本的答案,但我也想了解是否有适用于较新 .NET 版本的新方法。
谢谢!
public void DoProcess()
{
object locker = new object();
bool problematicCodeFinished = false;
Exception methodException = null;
Result result;
Func<Result> getProblematicResult = new Func<Result>(() => problematicMethod()); //create delegate
//run problematic method it in thread
getProblematicResult.BeginInvoke((ar) => //callback
{
lock(locker)
{
try
{
result = getProblematicResult.EndInvoke();
}
catch (Exception ex)
{
methodException = ex;
}
finally
{
problematicCodeFinished = true;
Monitor.Pulse(locker);
}
}
}, null);
//do more processing in main thread
// ...
// ...
// ...
try
{
//here we must know what was the result of the problematic method
lock (locker)
{
if (!problematicCodeFinished) //wait for problematic method to finish
{
Monitor.Wait(locker);
}
}
//throw problematic method exception in main thread
if (methodException != null)
{
throw methodException;
}
//if we are here we can assume that we have a valid result, continue processing
// ...
// ...
// ...
}
catch (Exception ex) //for the problematic method exception, or any other exception
{
//normal exception handling for my processing
}
}
你让自己的生活变得艰难。请尝试改用 TPL 中的任务。
您的代码如下所示:
public void DoProcess()
{
var task = Task.Factory.StartNew(() => problematicMethod());
//do more processing in main thread
// ...
// ...
// ...
var result = task.Result;
}