How I can implement timeout for a block of code in asp.net application without using Task
or Thread
? I don't want create new threads because HttpContext
will be NULL
in another threads.
For example, following code will not work
var task = Task.Run(() =>
{
var test = MethodWithContext();
});
if (!task.Wait(TimeSpan.FromSeconds(5)))
throw new Exception("Timeout");
object MethodWithContext()
{
return HttpContext.Current.Items["Test"]; // <--- HttpContext is NULL
}
EDIT:
I don't want pass current context to method, because I will have a lot of nested methods inside method... so a lot of refactor must be done for this solution
EDIT2:
I have realized that I can assign current context to variable before creating new task and replace HttpContext
in task with this variable. This will be safe?
var ctx = HttpContext.Current;
var task = Task.Run(() =>
{
HttpContext.Current = ctx;
var test = MethodWithContext();
});
if (!task.Wait(TimeSpan.FromSeconds(5)))
throw new Exception("Timeout");
object MethodWithContext()
{
return HttpContext.Current.Items["Test"]; // now works correctly
}