开发者

Is this method thread safe?

I'm using MVC2 framew开发者_Python百科ork and Unity2 as the IOC container. I resolve an IHttpContextLocatorService instance using Unity as below.

  RootContainer.RegisterType<IHttpContextLocatorService, HttpContextLocatorService>(new ContainerControlledLifetimeManager());

The above gives me a "singleton" of HttpContextLocatorService.

GetCurrentContext() function has been called by many places within our application. I'm concerned that GetCurrentContext() is not thread safety. It is not easy to test this as I cannot recreate multiple threads consists of various RequestContext and Controller etc.

Can anyone please advice whether the method "GetCurrentContext()" is thread safety?

public class HttpContextLocatorService : IHttpContextLocatorService
{

    [Dependency]
    public IControllerLocatorService ControllerLocator { get; set; }


    [Dependency]
    public IRequestContextLocatorService RequestContextLocator { get; set; }

    public HttpContextBase GetCurrentContext()
    {
        Controller controller = null;

        try
        {
            controller = this.ControllerLocator.GetController(this.RequestContextLocator.GetCurrentRequestContext()) as Controller;
        }
        catch { }

        if (controller == null)
        {
            return new HttpContextWrapper(HttpContext.Current);
        }

        return controller.HttpContext;
    }
}


It's thread-safe if both implementations of IControllerLocatorService.GetController() and RequestContextLocator.GetCurrentRequestContext() are.

If they are stateful they (and your method by consequence) could be not thread-safe. IMO you have 2 options:

  • ensure that both those methods are thread-safe
  • make the GetCurrentContext method thread-safe locking access to the two dependencies
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜