我'm在计时器滴答事件中使用位图,一切都很慢,我该如何解决这个问题?

本文关键字:何解决 问题 解决 计时器 滴答 位图 事件 | 更新日期: 2023-09-27 18:16:22

In form1 top I did:

private volatile bool _workersEnabled;
private ConcurrentQueue<Bitmap> _imageBuffer;
Thread threadA;
Thread threadB;

在构造函数中:

_workersEnabled = false;
_imageBuffer = new ConcurrentQueue<Bitmap>();
threadA = new Thread(CaptureScreensEntryPoint);
threadB = new Thread(ConsumeScreensEntryPoint);

然后在按钮中单击事件:

private void StartRecording_Click(object sender, EventArgs e)
{
    ffmp.Start("test.avi", 25);
    _workersEnabled = true;
    threadA.Start();
    threadA.Start();
    //Disable the button, so we eliminate the possibility to start this twice (would throw an exception anyway).
    StartRecording.Enabled = false;
}

之后我又加了:

private void CaptureScreensEntryPoint()
{
    while(_workersEnabled)
    {
        Bitmap bitmap = (Bitmap)ScreenCapture.CaptureScreen(true);
        //Just add it to the queue.
        _imageBuffer.Enqueue(bitmap);
        //Wait a bit
        Thread.Sleep(40);
    }
}
private void ConsumeScreensEntryPoint()
{
    while (_workersEnabled)
    {
        Bitmap workItem = null;
        if (_imageBuffer.TryDequeue(out workItem))
        {
            ffmp.PushFrame(workItem);
            workItem.Dispose();
        }
        //Also wait a bit here. Don't want to eat up the entire processor.
        Thread.Sleep(10);
    }
}

例外是在threadA.Start();:

ThreadStateException:线程正在运行或终止;无法重新启动

System.Threading.ThreadStateException was unhandled
  HResult=-2146233056
  Message=Thread is running or terminated; it cannot restart.
  Source=mscorlib
  StackTrace:
       at System.Threading.Thread.StartupSetApartmentStateInternal()
       at System.Threading.Thread.Start(StackCrawlMark& stackMark)
       at System.Threading.Thread.Start()
       at ScreenVideoRecorder.Form1.StartRecording_Click(Object sender, EventArgs e) in d:'C-Sharp'ScreenVideoRecorder'ScreenVideoRecorderWorkingVersion'Form1.cs:line 152
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at ScreenVideoRecorder.Program.Main() in d:'C-Sharp'ScreenVideoRecorder'ScreenVideoRecorderWorkingVersion'Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

我怎么解决它?

我'm在计时器滴答事件中使用位图,一切都很慢,我该如何解决这个问题?

我不确定哪一个需要更长的时间:ScreenCapture.CaptureScreenffmp.PushFrame(bitmap)。由于它是位图,我假设ffmp不能那么快,它会消耗一些时间。

我会采用生产者/消费者的方法。你有线程A做截图,把它们推到ConcurrentQueue,从那里它们被线程B捡起,把它们推到ffmp。

一些示例代码(未经过测试,也不保证完全工作,因此可能需要做一些调整):

//We need this thread for cross-thread access, so we don't want it cached. 
private volatile bool _workersEnabled;
private ConcurrentQueue<Bitmap> _imageBuffer;
public Form1()
{
  InitializeComponent();
  ffmp = new Ffmpeg();
  sc = new ScreenCapture();
  _workersEnabled = false; 
  _imageBuffer = new ConcurrentQueue<Bitmpap>();
  threadA = new Thread(CaptureScreensEntryPoint);
  threadB = new Thread(ConsumeScreensEntryPoint);
}
private void StartRecording_Click(object sender, EventArgs e)
{
  _workersEnabled = true; 
  threadA.Start();
  threadB.Start();
  //Disable the button, so we eliminate the possibility to start this twice (would throw an exception anyway).
  StartRecording.Enabled = false;
}
private void CaptureScreensEntryPoint() 
{
  while(_workersEnabled)
  {
    Bitmap bitmap = (Bitmap)ScreenCapture.CaptureScreen(true);
    //just add it to the queue.
    _imageBuffer.Enqueue(bitmap);
    //wait a bit
    Thread.Sleep(40);
  }
}
private void ConsumeScreensEntryPoint() 
{
  while(_workersEnabled)
  {
    Bitmap workItem = null;
    if(_imageBuffer.TryDequeue(out workItem))
    { 
      ffmp.PushFrame(workItem);
      workItem.Dispose();
    }
    //Also wait a bit here. Don't want to eat up the entire processor.
    Thread.Sleep(10);
  }
}

确保设置_workersEnabledfalse当你想要停止工人,例如当窗体关闭,或者你有一个专门的按钮。您可能还想添加一些错误处理,并使两个线程的休眠周期可配置。


注意

我想我可以用TPL来做,但是这个更快一些。请随意调整解决方案或发布一个新的。

尝试将捕获代码放在单独的线程中。我也做过类似的桌面捕获应用程序,并且能够获得60帧/秒左右。