C# 在匿名回调中捕获异常
我不知道为什么这不起作用。我怀疑这与单独的工作线程有关。我还没有找到任何关于以这种方式捕获异常的工作 我想我可以创建一个任务对象,然后运行它,但我更愿意保留这个体系结构,因为其中包含的代码非常复杂C# 在匿名回调中捕获异常,c#,callback,try-catch,C#,Callback,Try Catch,我不知道为什么这不起作用。我怀疑这与单独的工作线程有关。我还没有找到任何关于以这种方式捕获异常的工作 我想我可以创建一个任务对象,然后运行它,但我更愿意保留这个体系结构,因为其中包含的代码非常复杂 public void MethodOne(){ try{ MethodTwo(response =>{ //Do something with the response }); } catch(Exception err
public void MethodOne(){
try{
MethodTwo(response =>{
//Do something with the response
});
}
catch(Exception error){
//This never executes when method two throws exception
}
}
public void MethodTwo(Action<Object> callback){
//Conduct async call to external server
AppServer.MakeCall( response =>{
if(response.IsValid)
callback(response.Object);
else
throw new FooException();
});
}
public void MethodOne(){
试一试{
方法二(响应=>{
//对回应做点什么
});
}
捕获(异常错误){
//当方法2抛出异常时,它从不执行
}
}
公共void方法二(操作回调){
//对外部服务器执行异步调用
AppServer.MakeCall(响应=>{
if(response.IsValid)
回调(response.Object);
其他的
抛出新的FooException();
});
}
因为这个程序是异步的,所以在MethodTwo
返回并且线程继续离开try
块并做更大更好的事情之前,回调甚至不会被调用。在可能遥远的将来,另一个线程正在调用回调
正如您自己所提到的,一种可能性是使用任务
,而不是使用回调。第三方物流的主要优势之一是如何处理错误。如果异步方法返回任务
,您不仅可以使用ContinueWith
(或wait
)添加回调,还可以处理这些continuation中的错误
使用回调处理此问题的方法是接受两个回调,一个在响应有效时调用,另一个在出现异常/错误时调用。对于调用者来说,这远不如使用try/catch漂亮,但在基于回调的模型中,这是最好的选择。Servy是正确的。因为它已经是异步的,所以可能不需要使用另一个线程或任务。但是你可以用a来做这个
public void MethodOne()
{
MethodTwo()
.ContinueWith(task =>
{
if (task.IsFaulted)
// Handle error in task.Exception
;
else
{
object obj = task.Result;
// Handle object
}
});
}
public Task<object> MethodTwo()
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
//Conduct async call to external server
AppServer.MakeCall(response =>
{
if (Response.IsValid)
tcs.TrySetResult(response.Object);
else
tcs.TrySetException(new FooException());
});
return tcs.Task;
}
为了繁荣,我选择了通过两次回调。一个代表成功,一个代表失败。我让他们都匿名,所以结果很整洁。
public void MethodOne()
{
MethodTwo(response =>
{
if (Response.IsValid)
callback(Response.Object);
else
throw new FooException(); // Or error handling directly
});
}
public void MethodTwo(Action<Response> callback)
{
//Conduct async call to external server
AppServer.MakeCall(response =>
{
callback(response);
});
}
public void MethodOne()
{
MethodTwo(response =>
{
if (response is FooException)
{
FooException exc = response as FooException;
}
else
{
// Handle response;
}
});
}
public void MethodTwo(Action<object> callback)
{
//Conduct async call to external server
AppServer.MakeCall(response =>
{
if (Response.IsValid)
callback(Response.Object);
else
callback(new FooException());
});
}