开发者

Returning a value from a function after an elapsed amount of time?

开发者 https://www.devze.com 2022-12-27 16:02 出处:网络
I have a web service in ASP.NET being called by a time-sensitive process.If the web service takes longer than N seconds to run I want to return from the call so the time sensitive operation can contin

I have a web service in ASP.NET being called by a time-sensitive process. If the web service takes longer than N seconds to run I want to return from the call so the time sensitive operation can continue. Is this p开发者_运维知识库ossible and if so what is the code for this?


Call your web service asynchronously.

http://ondotnet.com/pub/a/dotnet/2005/08/01/async_webservices.html


Have the web service call its long-running part in a separate thread. Then wait, kill it, and bail if it takes too long. Be forewarned this could leave scarce resources hooked (e.g., db connections, etc), but you can fix this too.

(sorry for the quick and dirty code, it's for demo, you should elaborate and add types, webservice specifics, etc.)

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号