我在ASP.NET中有一个由时间敏感的进程调用的Web服务。如果Web服务运行时间超过N秒,我希望从呼叫返回,以便可以继续进行时间敏感操作。这是可能的,如果是这样的代码是什么?
答案 0 :(得分:3)
答案 1 :(得分:1)
让Web服务在一个单独的线程中调用其长期运行的部分。然后等待,杀死它,并保释,如果它需要太长时间。预先警告这可能会留下稀缺的资源(例如数据库连接等),但你也可以解决这个问题。
(抱歉快速而脏的代码,它是用于演示,你应该详细说明并添加类型,webservice细节等。)
dim ResultFromWorker as String
dim DoneWorking as boolean
sub GetWebServiceMagicNumber
DoneWorking = False
dim t as new thread = addressof (GetWebServiceMagicNumber_Worker)
t.start
dim count as integer = 0
while not DoneWorking and Count <100
count +=1
System.Threading.Thread.Sleep(100) ' Important to not kill CPU time
wend
if DoneWorking then
return ResultFromWorker
else
return "TimeOut"
EndIf
end sub
sub GetWebServiceMagicNumber_Worker
try
ResultFromWorker = SearchTheWholeWorldForTheAnswer()
catch ex1 as ThreadAbortException
' ignore - My code caused this on purpose
' calling thread should clean up scarce resources, this is borrowed time
catch ex2 as Exception
ResultFromWorker = "Error - " & ex.tostring
finally
DoneWorking=True
End Try
end sub