Search code examples
c#task-parallel-libraryargumentexception

Custom task runner method throws ArgumentException


Because of the fact that CultureInfo is not being copied from thread to thread I have made following method to do that thing for me.

public static StartCustomTask(Action action, TaskCreationOptions tco = TaskCreationOptions.None)
{
    var currentCult = Thread.CurrentThread.CurrentCuture;
    var currentUiCult = Thread.CurrentThread.CurrentUICulture;

    return Task.Factory.StartNew(() =>
    {
        Thread.CurrentThread.CurrentCuture = currentCult;
        Thread.CurrentThread.CurrentUICulture = currentUiCult;
        action();
    }, tco);
}

basically this code copies culture info from current thread to the thread that is gonna execute the action. I don't know why but it throws System.ArgumentException saying Value does not fall within the expected range. I've tried to run the action itself regularly on the main thread and it goes perfectly. By that I mean, that method that is being an action does not have a problem itself there is a problem somewhere in the code above I guess.

here is the stack trace of an exception

at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
   at System.Web.HttpRequest.BuildUrl(Func`1 pathAccessor)
   at System.Web.HttpRequest.get_Url()
   at SL.CoreLogic.Web.FrontEnd.Controllers.AccountController.<>c__DisplayClass37.<ResetPassword>b__31() in d:\CoreProjects\CoreLogic\CoreLogic-RusSlot\SL.CoreLogic\SL.CoreLogic.Web.FrontEnd\Controllers\AccountController.cs:line 447
   at SL.CoreLogic.Common.CustomTask.<>c__DisplayClass1.<StartWithCurrentCulture>b__0() in d:\CoreProjects\CoreLogic\CoreLogic-RusSlot\SL.CoreLogic\SL.CoreLogic.Common\CustomTask.cs:line 22
   at System.Threading.Tasks.Task.

and one more thing. this code was working perfectly but all of a sudden it started doing this.


Solution

  • I got it. the problem was that the action contained a line like this Url = Request.Url, as I guess at the time code was being executed the Request object did not exist or was not set.