views:

29

answers:

1

Hi, I'm seeing this code in a project and I wonder if it is safe to do:

(ASP.NET MVC 2.0)

class MyController
{
  void ActionResult SomeAction()
  {
    System.Threading.Thread newThread = new System.Threading.Thread(AsyncFunc);
    newThread.Start();
  }

  void AsyncFunc()
  {
    string someString = HttpContext.Request.UrlReferrer.Authority + Url.Action("Index", new { controller = "AnotherAction" } );     
  }
}

Is the controller reused, possibly changing the content of HttpContext.Request and Url, or is this fine (except for not using the thread pool).

Thanks for info!

A: 

Even if this is valid and works fine now, it just seems risky. The API and/or underlying implementation could always change in a future version, which might cause this code to break.

A much better practice is to pass any required data to the new thread in SomeAction when it is being spawned. For example, by using ParameterizedThreadStart as demonstrated in Passing Parameters to Threads.

Justin Ethier
This is correct. The Controller type (and HttpContext itself) aren't thread-safe. This could throw an exception, even if all you're doing is reading data. And unhandled exceptions on ThreadPool threads could bring down the entire worker process, killing any other requests that your application happens to be serving at the time.
Levi
But you are not saying the same thing. Justin thinks it should be OK (but not a good idea) while you think it might throw.
No, all I said was *even if* it works fine now... so I think it might throw as well :)
Justin Ethier