I am missing an important concept, and I would really appreciate help. I hope I can describe my problem properly, I am new to posting on forums and asking for help.
I have an async task in a Camera class that streams a bitmap from a RTSP stream to a Picture Box in my UI.
I use Safe Fire and Forget when I start the streaming task so I can continue on the UI thread.
I don’t want to have await and async all over my form, it became unmanageable and interfered with other threads. The UI is responsive and it works well.
Now, I subscribe to a SnapShotTaken event on the Camera class when I want to take a snapshot. I then call a function on the Camera class to tell it to begin taking the snapshot (by setting a Boolean variable), and then I want the UI thread to wait for the event to be fired on my form.
I am using a loop with Thread.Sleep on the UI which then locks up the UI and the Camera class!
How can I wait for the callback, and let the Camera class continue it’s work (which I assumed to be on a background thread since I did not await it) to signal me, without me blocking the Camera class work?
Here is the code to subscribe to the Camera class (ThisFormIPCamera) from a Button Click event
ThisFormIPCamera.SnaphotTaken += ThisFormIPCamera_RegSnaphotTaken;
ThisFormIPCamera.TakeSnapshot();
Here is the code of TakeSnapshot in the Camera class which just sets a variable to tell the Camera class
to take the next frame received and send it back to me.
public void TakeSnapshot()
{
_takeSnapshot = true;
}
The code on the UI to wait which is obviously not good:
int timeoutCounter = 0;
while (!RegPhotoTaken)
{
try
{
System.Threading.Thread.Sleep(200);
}
timeoutCounter++;
if (timeoutCounter > 50)
{
MessageBox.Show("Timeout", GlobalVars.APP_NAME, MessageBoxButtons.OK)
break;
}
}
This code times out and only with the MessageBox does the code on the Camera class continue and I get my picture.
What can I use that won’t allow the UI code to execute, but allow the task on the camera class to run.
Thank you!
I have tried starting using async and await on the functions that contain the calls to subscribe to the event on the Camera class but it became very complicated all over the form and my analog camera gave issues.
I tried to set flags to stop other threads working, but I would like a cleaner solution if possible.