Search code examples
vb.netfor-loopterminate

For Loop: Skip to next line after X seconds


Can someone help me with this code:

I have a dataGrid with 2 columns:
My grid

and what I want to do is use PStools' Psloggedon cmd to give me the name of every person logged in and append that result to the "LOGGED_IN" column but what is happening is that if there is no user logged into a PC, the process takes like 5 minutes to post an error message.

Now, what I want to do is that if .5 seconds has gone to just forget the row it's currently querying and move on to the next row, in the column?

here is the vb.net code i want to focus on:

  Dim RowCount As Integer = datagridView1.RowCount  
  For i = 0 To RowCount - 2
        'PERFORM PSLOGGEDON ROUTINE
        Dim Proc1 As New Process
        Proc1.StartInfo = New ProcessStartInfo("psloggedon")
        Proc1.StartInfo.Arguments = "-l \\" & datagridView1.Rows(i).Cells(0).Value & ""
        Proc1.StartInfo.RedirectStandardOutput = True
        Proc1.StartInfo.UseShellExecute = False
        Proc1.StartInfo.CreateNoWindow = True
        Proc1.Start()

        'INSERT RESULTS IN LOGGEN_IN COLUMN
        datagridView1.Rows(i).Cells(1).Value = Proc1.StandardOutput.ReadToEnd
    Next

Can someone please show me how to write the code to get that done?


Solution

  • Use Process.WaitForExit(int milliseconds) method.

    Instructs the Process component to wait the specified number of milliseconds for the associated process to exit.

    Return Value
    Type: System.Boolean

    true if the associated process has exited; otherwise, false.

    You can then use Process.Kill to kill process if it did not exit in given time.

    Something like

    Dim RowCount As Integer = datagridView1.RowCount  
    For i = 0 To RowCount - 2
        'PERFORM PSLOGGEDON ROUTINE
        Dim Proc1 As New Process
        Proc1.StartInfo = New ProcessStartInfo("psloggedon")
        Proc1.StartInfo.Arguments = "-l \\" & datagridView1.Rows(i).Cells(0).Value & ""
        Proc1.StartInfo.RedirectStandardOutput = True
        Proc1.StartInfo.UseShellExecute = False
        Proc1.StartInfo.CreateNoWindow = True
        Proc1.Start()
    
        If Not Proc1.WaitForExit(5000) Then
            Proc1.Kill()
        End If
    
        'INSERT RESULTS IN LOGGEN_IN COLUMN
        datagridView1.Rows(i).Cells(1).Value = Proc1.StandardOutput.ReadToEnd
    Next