仍在努力掌握WPF中的多线程。当事件处理程序附加到事件时,它(事件处理程序)是否与事件在同一个线程上运行?
例如,在NAudio,我的理解是WasapiCapture直接与麦克风设备驱动程序一起工作:(代码取自GitHub):
capture = new WasapiCapture(SelectedDevice);
capture.ShareMode = ShareModeIndex == 0 ? AudioClientShareMode.Shared : AudioClientShareMode.Exclusive;
capture.WaveFormat =
SampleTypeIndex == 0 ? WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channelCount) :
new WaveFormat(sampleRate, bitDepth, channelCount);
currentFileName = String.Format("NAudioDemo {0:yyy-MM-dd HH-mm-ss}.wav", DateTime.Now);
RecordLevel = SelectedDevice.AudioEndpointVolume.MasterVolumeLevelScalar;
// In NAudio, StartRecording will start capturing audio from an input device.
// This gets audio samples from the capturing device. It does not record to an audio file.
capture.StartRecording();
capture.RecordingStopped += OnRecordingStopped;
capture.DataAvailable += CaptureOnDataAvailable;
当数据缓冲区已满(?)时,WasapiCapture会引发CaptureOnDataAvailable事件处理程序所附加的DataAvailable事件。为了拥有事件处理程序CaptureOnDataAvailable,更新UI,我不得不使用synchronizationContext:
synchronizationContext = SynchronizationContext.Current;
然后:
private void CaptureOnDataAvailable(object sender, WaveInEventArgs waveInEventArgs)
{
// I'M GUESSING I AM IN A BACKGROUND THREAD HERE?
// Here, I am scheduling a UI update on the UI thread.
synchronizationContext.Post(s => UpdateGraph(waveInEventArgs), null);
}
那么,我是否正确假设事件处理程序将在它所连接的同一个线程上运行?
TIA