简体   繁体   中英

How can I lock my object using C# in dll

I have an i/p camera and a function that is repeating and receiving each frame.

public Bitmap ProcessFrame(Bitmap frame)
{

} 

Here is the buffering place I am buffering last 100 bitmaps:

lock (writer)
{
   BM[now] = new Bitmap(frame);
   now = (now == 99) ? 0 : now + 1;
}

When I press record to record video, I need to save every buffered bitmaps and after that I have to save incoming bitmaps that are received after pressing record. So when I press Record and using the code below to save buffered bitmaps to video file I lose some of my incoming frames. The incoming frames while processing this section, are dropped and I don't want to drop them.

lock (writer)
{
   for (int i = now; i < 150; i++)
   {
      if (BM[i] == null)
        break;
      writer.WriteVideoFrame(BM[i]);//adding frame to an existing open file
   }
   if (now != 0)
   {
      for (int i = 0; i < now - 1; i++)
      {
         writer.WriteVideoFrame(BM[i]);//adding frame to an existing open file
      }
   }
}

Here is the part for incoming frames to be saved in video file

 lock (writer)
 {
    writer.WriteVideoFrame(frame);//adding frame to an existing open file
 }

I have searched and found that lock will help me. When saving buffered bitmaps lock will lock writer so another bitmap that has come will be stop at writer and wait to be unlocked, but it did not help.

What should I do? how can I make a safe thread? I am using opensource ispy and i think it will make thread for each frame and call this thread. Help me to save my incoming frame.

Instead of using a silly fixed array type solution, why not use ConcurrentQueue? Then you won't have to deal with threading since that's a thread safe class. Have one thread pulling frames from the head of the queue and writing them and have the other thread add.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM