线程任务未在IIS中执行

时间:2014-09-23 07:31:59

标签: c# asp.net-mvc multithreading iis task

我有一个使用Forms身份验证模式的.Net应用程序,并且有一个调用异步任务的函数。以下是任务的片段:

Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);

当我在Visual Studio IDE上测试时,线程正常工作。问题是当我部署它时,系统似乎跳过或不执行线程化任务。

我读过一篇文章,说这可能是由IIS中的权限引起的:

http://codemine.net/post/Thread-Not-working-in-Aspnet-When-deployed-to-IIS

调整上面文章中要在Forms身份验证中实现的解决方案,下面是代码:

[System.Runtime.InteropServices.DllImport("advapi32.dll", EntryPoint = "LogonUser")]
private static extern bool LogonUser(
         string lpszUsername,
         string lpszDomain,
         string lpszPassword,
         int dwLogonType,
         int dwLogonProvider,
         ref IntPtr phToken);

    public JsonResult uploadimages(){

         try{

            IntPtr token = new IntPtr(0);
                        token = IntPtr.Zero;

                        bool returnValue = LogonUser("Administrator", "WIN-82CH4949B3Q", "Neuron14",
                                         3,
                                         0,
                                         ref token);

            WindowsIdentity newId = new WindowsIdentity(token);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();

            var task2 =     Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);

            impersonatedUser.Undo();

            return Json(new { message = "Success" }, "text/plain; charset=utf-8");

         }

         catch (ex Exception)
         {
            return Json(new { error= ex.Message }, "text/plain; charset=utf-8");
         }
    }

实现上述代码到系统仍然不会在IIS中部署后执行该线程。我真的很难解决这个问题,因为我不知道线程在部署时没有执行的原因。

1 个答案:

答案 0 :(得分:0)

尝试模拟Windows标识时出现问题:

WindowsIdentity newId = new WindowsIdentity(token);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();

var task2 =     Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);

impersonatedUser.Undo();

问题是Impersonate函数仅适用于该线程,而UploadFunction正在另一个线程上运行。

以下是对您的代码的修改,该代码在后台任务的主题中调用了Impersonate方法:

WindowsIdentity newId = new WindowsIdentity(token);
var task2 = Task.Factory.StartNew(() => 
                                 {
                                     using(WindowsImpersonationContext wi = newId.Impersonate())
                                     {
                                          UploadFunction();
                                     }
                                 },
                                 tokenSource.Token,
                                 TaskCreationOptions.LongRunning,
                                 TaskScheduler.Default
                               );

我的猜测是它在本地计算机上运行,​​因为您上传到允许匿名访问的文件夹。生产服务器上的权限会更加严格。