线程任务未在IIS中执行
本文关键字:执行 IIS 任务 线程 | 更新日期: 2023-09-27 18:24:11
我有一个.Net应用程序,它使用Forms Authentication模式,并具有一个调用异步任务的函数。以下是任务片段:
Task.Factory.StartNew(() => { UploadFunction(); }, tokenSource.Token, TaskCreationOptions.LongRunning,TaskScheduler.Default);
当我在VisualStudioIDE上进行测试时,线程运行良好。问题是,当我部署它时,系统似乎跳过或不执行线程任务。
我读过一篇文章,这可能是由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中,将上述代码实现到系统仍然不会执行线程。我真的很难解决这个问题,因为我真的不知道为什么线程在部署时没有执行。
尝试模拟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
);
我的猜测是,它在你的本地机器上工作,因为你正在上传到一个允许匿名访问的文件夹。生产服务器上的权限会严格得多。