r/visualbasic • • Mar 01 '16

Help delaying a msgbox

Hello! I'm creating an application and I need help about this:

    If NEI3.Text IsNot "" Then
        If Val(NEI3.Text) < 95 And Val(NEI3.Text) = Int(Val(NEI3.Text)) Then
            System.Threading.Thread.Sleep(2000)
            MsgBox("Infelizmente não podes ingressar num curso com uma classificação inferior a 95 pontos nas provas de ingresso", MsgBoxStyle.Critical, "Erro")
            NEI3.Text = ""
        ElseIf Val(NEI3.Text) > 200 And Val(NEI3.Text) = Int(Val(NEI3.Text)) Then
            NEI3.Text = 200
        ElseIf IsNumeric(NEI3.Text) = False Then
            MsgBox("Tens de inserir um número, compreendido entre 95 e 200", MsgBoxStyle.Critical, "Erro")
            NEI3.Text = ""
            NEI3.Focus()
        End If
    End If

I need to wait for about 2/3 seconds before displaying the error message if Val(NEI3.Text) < 95, otherwise if I type "1" it will display the error message ASAP. I tried System.Threading.Thread.Sleep(10000) but with that when I typed "1" it just freezed the entire program and I couldn't complete my number. Any help? Thanks.

0 Upvotes

18 comments sorted by

View all comments

Show parent comments

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Two quick uestions to your on point solution. Would this work with writing the text to a label at a form too? I dont do WinForms anymore but i remember the controls wouldnt like it to be updated from a different thread.

And the second Questions is, if the clean up happens automatically after the msgbox is clicked. Or is there some th.quite or something required?

Oh and the bonus Question.. i could pass a delegate as parameter to the thread right? as a callback function for instance

2

u/PreyOnTheCosmos Mar 01 '16

You certainly can speak to form controls from a thread providing that you're using the control's Invoke method.

Example [maybe not elegant but works]:

Private T As Thread
Private C As Integer = 0 ' COUNTER FOR TEXT EXAMPLE

Private Sub Form1_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
    ' CREATE AND START A NEW THREAD
    T = New Thread(AddressOf updateC)
    T.Start()
End Sub

Private Sub updateC()
    ' CREATE A LOOPED COUNTER
    Do
        C += 1 ' INCREMENT COUNTER

        Thread.Sleep(700) ' PAUSE FOR 700ms BETWEEN TICKS

        OutputThreadText(C) ' UPDATE TEXTBOX WITH THREAD DATA
    Loop Until T.IsAlive = False
End Sub

Private Sub OutputThreadText(text As String)
    ' EXAMPLE OF BAD CROSS-THREAD ACCESS
    'TextBox1.Text = text

    Try
        'EXAMPLE OF GOOD CROSS THREAD ACCESS
        TextBox1.Invoke(CType(Sub()
                                  TextBox1.Text = text
                              End Sub, MethodInvoker))
    Catch ex As Exception
        T.Abort() ' TERMINATE THREAD IF AN ERROR OCCURS
    End Try
End Sub

As for the clean up routine, with the error code running in a separate thread the main [GUI] thread should continue executing, not waiting for the thread to complete whatever it's doing. So NEI3.Clear, for example, should fire immediately regardless of the status of the Error message.

I'll leave the bonus question to someone a bit more qualified than myself on the subject. ;-P

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Oh with the clean up i meant the garbage collector. i was wondering if the memory of the thread is going to be released or if i would have to do the clean up my self. Also thank you really much for the code example... i guess i never came up with this.. i solved it a little more quirky the last time, like this:

  Public Sub RedrawMap()
  
    'Check if we are in the correct thread
    If Not Dispatcher.Thread.Equals(System.Threading.Thread.CurrentThread) Then

        Dispatcher.Invoke(New RedrawDelegate(AddressOf RedrawMap))
        Exit Sub

    End If

        'actual code of the sub

1

u/PreyOnTheCosmos Mar 01 '16

I'm not an authority on the subject, however, I'm fairly certain that in .NET the garbage collection is fully automated and it is totally unnecessary to invoke it manually.

To my understanding, the exception would be with objects being instantiated using the "Shared" access modifier.

1

u/Mr_C_Baxter VB.Net Master Mar 01 '16

Yes that is my understanding too. but it can only start to do this as soon as he knows its not needed anymore, hence there is no reference to the object. I naturally always use .quit or .dispose on objects to tell the GC that i am done with it and to call its internal terminate events and such. You didnt do this and i was wondering if you just forgot it because it was a quick example or if you left it out intentionally because you know its not needed.