gpt4 book ai didi

c# - 为什么没有捕获异常?

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:19 26 4
gpt4 key购买 nike

我认为我的理解中缺少一些东西。如果我在 Console.WriteLine 完成的 catch 中放置一个断点,它不会停止。

private static void Main(string[] args)
{
Process(async () => await ClientMethod()).Invoke();
Console.Read();
}

public static async Task ClientMethod()
{
throw new Exception("Test");
}

public static Action Process(Action functor)
{
return () =>
{
try
{
functor();
}
catch (Exception)
{
// Handle exceptions ?
Console.WriteLine("In the catch");
throw;
}
};
}

但是如果我将我的代码更改为这样,通过删除异步行为,断点就会命中:

private static void Main(string[] args)
{
Process(() => ClientMethod()).Invoke();
Console.Read();
}

public static void ClientMethod()
{
throw new Exception("Test");
}

为什么第一种情况没有捕获到异常?我怎样才能捕获它?

编辑:我将我的代码改成了这个,但它仍然是一样的:

private static void Main(string[] args)
{
var res = Process(async () => await ClientMethod()).Invoke();
Console.Read();
}

public static async Task<string> ClientMethod()
{
throw new Exception("Test");
}

public static Func<T> Process<T>(Func<T> functor)
{
return () =>
{
try
{
return functor();
}
catch (Exception)
{
// Handle exceptions ?
Console.WriteLine("In the catch");
throw;
}
};
}

最佳答案

因为 Process 中的操作被调用为 async void .

引用:来自Async/Await - Best Practices in Asynchronous Programming

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task<T> method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

关于c# - 为什么没有捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41979621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com