Click here to Skip to main content
15,886,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I have a code that sometimes stuck in very long process, sadly it is one of my most needed .dll so I cannot get rid of it altogether.
Let's call it unreliableLongProcess()

What I want is to set a timeout for that process, so if it is taking more than 10 minutes (or any other set timeout), I would like it to give up so it does not hinder the rest of codes to run. How do I do this?


My thought it would be something like this :

Dim stopwatch As Stopwatch = New Stopwatch()
stopwatch.Start()
While stopwatch.ElapsedMilliseconds < 10000
     unreliableLongProcess()
End While


How should I do this?
Any helps will be much appreciated, thank you.

What I have tried:

Dim stopwatch As Stopwatch = New Stopwatch()
stopwatch.Start()
While stopwatch.ElapsedMilliseconds < 10000
     unreliableLongProcess()
End While
Posted
Updated 6-Jul-20 17:47pm

The easiest way to do this would be to move your long running code to a Task.


A CancelationTokenSource already has an implementation for CancelAfter(milliseconds), so this is pretty easy to do.

Cancel Async Tasks after a Period of Time (C#) | Microsoft Docs[^]
 
Share this answer
 
Following from Dave's suggestion, I 'think' (*tm, I'm not a VB.Net Programmer) you could do something like

' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource

Private Async Sub unreliableLongProcess() as Task()

  ' Instantiate the CancellationTokenSource.
  cts = New CancellationTokenSource()

  Dim token as cts.Token
  Try
    ' Set up the CancellationTokenSource to cancel after 10 * 60 * 1000 = 10 minutes. 
    cts.CancelAfter(10*60*1000)

    ' ? is this Await redundant ?
    Await Task.Run(Sub()
      '
      ' Do slow processing here
      ' 
      token.ThrowIfCancellationRequested()
    End Sub, token)

    ' Log/Display Process is Complete

    Catch ex As OperationCanceledException
    ' Log/Display Process Canceled/Timed Out

    Catch ex As Exception
    ' Log/Display Some Other Exception Occurred
  End Try

  ' Set the CancellationTokenSource to Nothing when the process is complete.
  cts = Nothing
End Sub
And use it as in
Await unreliableLongProcess()
(I was thinking about Async, Await etc in C# before Dave answered)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900