2011-02-18 60 views
4

我有一个简单的形式的ASP.NET页面。用户用一些细节填写表单,上传文档,然后需要在服务器端进行一些文件处理。如何从ASP.NET页面运行冗长的任务?

我的问题是 - 什么对处理文件的服务器端处理的最佳方法?处理涉及调用一个exe文件。我应该使用单独的线程吗?

理想我希望用户提交表单,而不同时处理发生的网页只是挂在那里。

我试过这个代码,但我的任务从来没有在服务器上运行:

Action<object> action = (object obj) => 
{ 
     // Create a .xdu file for this job 
     string xduFile = launcher.CreateSingleJobBatchFile(LanguagePair, SourceFileLocation); 

     // Launch the job     
     launcher.ProcessJob(xduFile); 
}; 

Task job = new Task(action, "test"); 
job.Start(); 

任何建议表示赞赏。

回答

7

你可以在一个典型的火异步调用的处理功能,而忘记时尚:

在.NET 4.0你应该这样做,使用新Task Parallel Library

Task.Factory.StartNew(() => 
{ 
    // Do work 
}); 

如果您需要将参数传递给动作代表你可以做这样的:

Action<object> task = args => 
{ 
    // Do work with args 
};  
Task.Factory.StartNew(task, "SomeArgument"); 

在.NET 3.5和更早你反而会做这种方式:

ThreadPool.QueueUserWorkItem(args => 
{ 
    // Do work 
}); 

相关资源:

+0

我已经使用类似的方法试过,但我的任务从来没有在服务器上运行,我已经添加了我的问题的代码。我究竟做错了什么? – 2011-02-18 14:54:25

2

用途:

ThreadPool.QueueUserWorkItem(o => MyFunc(arg0, arg1, ...)); 

凡MYFUNC()不会在用户后,后台服务器端处理提交页面;

1

我有一个网站有一些潜在的长期运行需要响应的东西并更新用户的计时器。

我的解决办法是建立一个状态机进入页面带有隐藏值和一些会话值。

我有这些对我的aspx方:

<asp:Timer ID="Timer1" runat="server" Interval="1600" /> 
<asp:HiddenField runat="server" ID="hdnASynchStatus" Value="" /> 

我的代码看起来是这样的:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    PostbackStateEngineStep() 
    UpdateElapsedTime() 
End Sub 

Private Sub PostbackStateEngineStep() 
    If hdnASynchStatus.Value = "" And Not CBool(Session("WaitingForCallback")) Then 

     Dim i As IAsyncResult = {...run something that spawns in it's own thread, and calls ProcessCallBack when it's done...} 

     Session.Add("WaitingForCallback", True) 
     Session.Add("InvokeTime", DateTime.Now) 
     hdnASynchStatus.Value = "WaitingForCallback" 
    ElseIf CBool(Session("WaitingForCallback")) Then 
     If Not CBool(Session("ProcessComplete")) Then 
      hdnASynchStatus.Value = "WaitingForCallback" 
     Else 
      'ALL DONE HERE 
      'redirect to the next page now 
      response.redirect(...) 
     End If 
    Else 
     hdnASynchStatus.Value = "DoProcessing" 
    End If 
End Sub 
Public Sub ProcessCallBack(ByVal ar As IAsyncResult) 
    Session.Add("ProcessComplete", True) 
End Sub 
Private Sub UpdateElapsedTime() 
    'update a label with the elapsed time 
End Sub