我只是一个简单的vb.net网站,需要调用一个Sub执行一个非常长的任务,可以同步文件系统中的一些目录(细节不重要).
当我调用该方法时,最终会在网站上等待子程序完成.然而,即使网站超时,例行程序最终完成任务,所有的目录都应该是最终的.
我想防止超时,所以我只想异步地调用Sub.我不需要(甚至想要)和回调/确认它成功运行.
如果你需要一些代码:
Protected Sub Page_Load(ByVal sender As Object,ByVal e As System.EventArgs) Handles Me.Load Call DoAsyncWork() End Sub Protected Sub DoAsyncWork() Dim ID As String = ParentAccountID Dim ParentDirectory As String = ConfigurationManager.AppSettings("AcctDataDirectory") Dim account As New Account() Dim accts As IEnumerable(Of Account) = account.GetAccounts(ID) For Each f As String In My.Computer.FileSystem.GetFiles(ParentDirectory) If f.EndsWith(".txt") Then Dim LastSlashIndex As Integer = f.LastIndexOf("\") Dim newFilePath As String = f.Insert(LastSlashIndex,"\Templates") My.Computer.FileSystem.CopyFile(f,newFilePath) End If Next For Each acct As Account In accts If acct.ID <> ID Then Dim ChildDirectory As String = ConfigurationManager.AppSettings("AcctDataDirectory") & acct.ID If My.Computer.FileSystem.DirectoryExists(ChildDirectory) = False Then IO.Directory.CreateDirectory(ChildDirectory) End If My.Computer.FileSystem.DeleteDirectory(ChildDirectory,FileIO.DeleteDirectoryOption.DeleteAllContents) My.Computer.FileSystem.CopyDirectory(ParentDirectory,ChildDirectory,True) Else End If Next End Sub
我不建议使用Thread类,除非你需要更多的控制线程,因为创建和拆除线程是昂贵的.相反,我建议您使用
a ThreadPool thread.
See this阅读.
原文链接:https://www.f2er.com/vb/255684.html您可以在ThreadPool线程上执行您的方法,如下所示:
System.Threading.ThreadPool.QueueUserWorkItem(AddressOf DoAsyncWork)
您还需要将您的方法签名更改为…
Protected Sub DoAsyncWork(state As Object) 'even if you don't use the state object
最后还要注意,其他线程中的未处理的异常会杀死IIS.请参阅this article(旧但仍然相关;不确定解决方案,因为我不会使用ASP.NET).