C# 使用MediaCapture的摄像头流在一段时间后停止工作?

C# 使用MediaCapture的摄像头流在一段时间后停止工作?,c#,wpf,uwp,windows-10,C#,Wpf,Uwp,Windows 10,我正在使用Windows.Media.Capture.MediaCapture从Surface网络摄像头获取视频流,并将其显示在屏幕上 await _mediaCap.InitializeAsync(new MediaCaptureInitializationSettings { VideoDeviceId = devices?.FirstOrDefault()?.Id, StreamingCaptureMode = StreamingCaptureMode.Video,

我正在使用
Windows.Media.Capture.MediaCapture
从Surface网络摄像头获取视频流,并将其显示在屏幕上

await _mediaCap.InitializeAsync(new MediaCaptureInitializationSettings
{
    VideoDeviceId = devices?.FirstOrDefault()?.Id,
    StreamingCaptureMode = StreamingCaptureMode.Video,
    PhotoCaptureSource = PhotoCaptureSource.VideoPreview
});

await _mediaCap.VideoDeviceController.SetMediaStreamPropertiesAsync(
    MediaStreamType.VideoPreview, encodeProps);

_dRequest = new DisplayRequest();
_dRequest.RequestActive();
我定期使用以下方法从摄影机流中获取一帧:

using (var randomAccessStream = new InMemoryRandomAccessStream())
{
    await Application.Current.Dispatcher.Invoke(async () =>
    {
        await _mediaCap.CapturePhotoToStreamAsync(properties, randomAccessStream);
    });

    await Task.Run(() => 
    { 
         randomAccessStream.Seek(0);
         using (var ioStream = randomAccessStream.AsStream())
         {
             BitmapImage bitmapImage = new BitmapImage();
             bitmapImage.BeginInit();
             bitmapImage.StreamSource = ioStream;
             bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
             bitmapImage.EndInit();
             bitmapImage.Freeze();

             capturedImage = bitmapImage;
         }
     });
}
一段时间后,流失败,出现异常:

"The request is invalid in the current state. Started"
为此,建议确保调用
capturepototostreamasync
的线程是UI线程(如上所示),但我仍然会遇到这个问题。就发生前的时间而言,它似乎是半随机的,在发生前20分钟到几个小时之间


请注意,这是一个WPF应用程序(.NET 4.6.2),用于利用
MediaCapture
类。

在我的情况下,有必要按顺序跟踪故障数量,如果故障达到某个阈值,则处理摄像头并重置依赖于摄像头的控件

  • CapturePreview
    对象上调用
    StopAsync()
  • MediaCapture
    对象上调用
    Dispose()
我发现,将我的相机预览
图像
控件放在一个经常被拆除和重建的视图中,要比将其放在我的“主视图”中并使其始终保持活动状态(如果它开始像上面那样发出垃圾邮件错误,则相同的
图像
用于重建相机)稳定得多

其他需要牢记的事项:

  • 注意哪些线程正在处理各种事情。当然,您需要UI线程来管理
    图像
    控件
  • 使用一个物体非常有助于确保相机不会被同时制造、放置或拍摄