DirectSound的例子程序CaptureSound(.NET version)的一个Bug

最近笔者在.NET平台上学着使用DirectSound来做一个简单的录音和WAV文件合并的功能, 当然DirectX自带的CaptureSound例子提供了一切录音的源代码,不过我发现其中有个Bug,导致Release版本的程序无辜退出。

DirectX SDK的版本: August 2007.
代码(位于文件MainForm.cs):
void InitNotifications()
{
  //-----------------------------------------------------------------------------
 
// Name: InitNotifications()
  // Desc: Inits the notifications on the capture buffer which are handled
  // in the notify thread.
  //-----------------------------------------------------------------------------
  if (null == applicationBuffer)
    throw new NullReferenceException();
  // Create a thread to monitor the notify events
  if (null == NotifyThread)
  {
    NotifyThread = new Thread(new ThreadStart(WaitThread));
    Capturing = true;
    NotifyThread.Start();
    // Create a notification event, for when the sound stops playing
    NotificationEvent = new AutoResetEvent(false);
 
  }
  // Setup the notification positions
  for (int i = 0; i < NumberRecordNotifications; i++)
  {
    PositionNotify[i].Offset = (NotifySize * i) + NotifySize - 1;
    PositionNotify[i].EventNotifyHandle = NotificationEvent.Handle;
  }
  applicationNotify = new Notify(applicationBuffer);
  // Tell DirectSound when to notify the app. The notification will come in the from
  // of signaled events that are handled in the notify thread.
  applicationNotify.SetNotificationPositions(PositionNotify, NumberRecordNotifications);
}

private void WaitThread()
{
  while(Capturing)
  {
    //Sit here and wait for a message to arrive
    NotificationEvent.WaitOne(Timeout.Infinite, true);
    RecordCapturedData();
  }
}
注意,在WaitThread被第一次调用的时,也就是代码 NotifyThread.Start(),这个时刻NotificationEvent还没有被初始化,而在WaitThread中就直接调用了这个变量!而Visual Studio的强大之处在于,在Debug模式下,CLR可能优先执行了主线程,也就是这个变量随即被初始化了,导致这个问题无法被发觉。而在Release模式下,无论怎么写Catch,这个异常都会直接终止程序。 
 
修正这个Bug非常简单:
   // Create a notification event, for when the sound stops playing
    NotificationEvent = new AutoResetEvent(false);
    NotifyThread.Start();  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值