[英]ExceptionHandler in c# WebAPI
I have a question regarding how exactly this thing works. 我有一个关于这个东西究竟是如何工作的问题。
public class GlobalExceptionHandler: ExceptionHandler
{
private string _pvtMsg;
public override void handle(ExceptionHandlerContext context)
{
//few if else conditions
if()
{
}
else if
{
_pvtMsg = "some value";
}
context.Result="Some random value depending upon if else execution";
}
}
Now when _pvtMsg
is set after that, whenever exception occurs it always have that same value as before. 现在,在
_pvtMsg
之后设置_pvtMsg
时,每当发生异常时,它总是具有与之前相同的值。
Does, when I set _pvtMsg = "a";
当我设置
_pvtMsg = "a";
in the else if
condition, the next time an error occurs _pvtMsg
still have value "a"
? 在
else if
条件下,下次发生错误时_pvtMsg
仍然有值"a"
?
Is there only a single instance of handler
available throughout the lifespan of my application and hence this is happening? 在我的应用
handler
整个生命周期中是否只有一个handler
实例可用,因此会发生这种情况? Or are there any other reasons? 还是有其他原因吗? Any documents for reference would be appreciated.
任何参考文件将不胜感激。
Btw: this handler is registered with the Register
method of the WebApiConfig
. 顺便说一句:这个处理程序是使用
WebApiConfig
的Register
方法Register
的。
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
Your assumption is correct. 你的假设是正确的。 Since you register an Instance of
GlobalExceptionHandler
(with the new
keyword) _pvrMsg
will always have the value of the previous (successful) call. 由于您注册了
GlobalExceptionHandler
的实例 (使用new
关键字), _pvrMsg
将始终具有上一个(成功)调用的值。
If _pvrMsg
is critical for whatever you are planning on doing in your if
block, I'd recommend locking this part of the code to make sure handle
doesn't execute multiple times at once. 如果
_pvrMsg
对于你在if
块中计划进行的操作至关重要,我建议锁定这部分代码以确保handle
不会一次执行多次。
The easiest way to do this would be: 最简单的方法是:
public class GlobalExceptionHandler: ExceptionHandler
{
private string _pvtMsg;
private readonly object _lock = new object();
public override void handle(ExceptionHandlerContext context)
{
lock(_lock)
{
//few if else conditions
if()
{
}
else if
{
_pvtMsg = "some value";
}
context.Result="Some random value depending upon if else execution";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.