gleb.kudr
gleb.kudr

Reputation: 1508

Only one thread at a time c#

I have a task with a huge amount of input data (video). I need to process its frames in the background without freezing the UI and I don't need to process every frame.

So I want to create a background thread and skip frames while background is busy. Than I get another frames from video input and again.

I have this simple code now. I worked. But can it cause troubles and may be there is a better approach?

public class VideoProcessor{

 bool busy=false;

 void VideoStreamingEvent(Frame data){
  if(!busy){
   busy=true;
   InvokeInBackground(()=>{
    DataProcessing(data);
    busy=false;
   });
  }
 }

}

Upvotes: 0

Views: 387

Answers (1)

Mike Strobel
Mike Strobel

Reputation: 25623

But can it cause troubles and may be there is a better approach?

If the VideoStreamingEvent method never executes concurrently on multiple threads, then this will work fine if you simply add volatile to the busy field declaration. It may, in practice, appear to work well enough without it, but that behavior is not guaranteed.

If it is possible for VideoStreamingEvent to be invoked on multiple threads, then you will need some synchronization around where you read and write the busy field.

Upvotes: 1

Related Questions