I am making a WinForms app in .net 4.0 (vb.net) and I would like to ask:
I am writing a piece of code that needs to run every specific interval. This task will firstly disable a button in the form and then do the work. At 2 points during this work, it must wait for 1sec and then proceed. When finished, it must re-enable the button.
During this whole procedure, I don't want to freeze the gui.
How should I implepent this? Must I use a background worker?
Feel free to answer me in c# or vb.net, whatever you like!
Thanks in advance!
EDIT: What I've done so far (I am using Aforge.NET framework to capture a camera screenshot):
I dragged a backgroung worker in the form. In its DoWork event, I entered the name of the main work:
Private Sub BackgroundWorker_camera_DoWork() Handles BackgroundWorker_camera.DoWork
do_evaluation()
End Sub
The do_evaluation sub must do some work, then wait for a second (for camera device to be ready), capture camera snapshot, wait for another second and finish work:
Public Delegate Sub do_evaluationDelegate()
Public Sub do_evaluation()
If Me.InvokeRequired Then
Me.Invoke(New do_evaluationDelegate(AddressOf do_evaluation))
Return
End If
ButtonX_Evaluate.Enabled = False
ButtonX_restore.Enabled = False
...some work...
evaluate_from_camera()
...some work...
Main.ButtonX_Evaluate.Enabled = True
Main.ButtonX_restore.Enabled = True
ReleaseMemory()
End Sub
And the evaluate from camera sub:
Public Delegate Sub evaluate_from_cameraDelegate()
Public Sub evaluate_from_camera()
If Me.InvokeRequired Then
Me.Invoke(New evaluate_from_cameraDelegate(AddressOf evaluate_from_camera))
Return
End If
Aforge_cam.start_source()
'wait for 1sec
Thread.Sleep(1000)
AddHandler Aforge_cam.videoSource.NewFrame, AddressOf Aforge_cam.video_NewFrame
'wait for 1sec
Thread.Sleep(1000)
Aforge_cam.CloseVideoSource()
End Sub
As the system requires a little time to connect to the hardware cam, the sub must wait for a second after the Aforge_cam.start_source()
command, in order for the hardware to initialize fully.
Then, adding the handler for a new frame capture event in evaluate _from_camera will cause a new frame to be captured in a public variable "screenshot". As it requires some tenths of a second to capture a frame from the webcam, the code must wait for a capture of a bitmap in screenshot variable in order to continue. Hence the 2 sleep commands.
I begin the process with a RunWorkerAsync
command to the background worker.
Nevertheless, the GUI freezes and I cannot understand why, since background workers run on a separate thread, right?