[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 266
  • Last Modified:

Threading in .NET 4

I have a scenario as follow in Windows Product based application using .net 4.
1. A VB.NET project consists of one usercontrol with a few controls in it.
2. I load this control (once or many) times on the main form as in Me.Controls.Add(usercontrol)
3. The project has a timer which updates a label control in the usercontrol for every tick (every 1000 ms) which gets initiated in the Main form
4. I do also have a button on the main form with a separate task say Thread.Sleep or loop untill the elapsed time using stopwatch crosses 5000 ms and then comes out of the button click event
5. Now When I click this button my control which is getting updated by a timer in the usercontrol ALSO stops untill the button click event completes. It is as if the entire application gets suspended for a while (5 secs).

NOW I would need the timer control to update the label control in the usercontrol IRRESPECTIVE of any process that is running through the main form.
I would need a seamless update to the label in the user control.

I have tried with multiple threads et al. Nevertheless whenver the main form or the main thread does some job then the other controls say a timer update etc...stops for a while until the main form is free.

I would like to know how to keep updating the label control in the user control (say a timer updates the elapsed time in the label control) even when I click the button from the main form which does a loop for 5 seconds etc....

Please do let me know how to go about it.

Thank You
1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
In #4, you are locking up the main UI thread with your Sleep() call and/or looping structure, preventing the labels from being updated.

I think you want a five second delay within your button handler?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' ... some code ...
        Dim dt As DateTime = DateTime.Now.AddSeconds(5)
        While dt > DateTime.Now
            System.Threading.Thread.Sleep(100) ' <-- SMALL delay to reduce CPU usage
            Application.DoEvents() ' <-- Keep the app responsive during the pause
        End While
        ' ... some more code ...
    End Sub

Open in new window

ravindrasenAuthor Commented:
Good, had a tough time with the UI responsiveness in .NET 4 and win 7.

Thanks Idle_Mind

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now