0

Still trying to get a good grasp on multithreading in WPF. When an eventhandler is attached to an event, is it (the eventhandler) run on the same thread as the event?

For example, in NAudio, it is my understanding that the WasapiCapture works directly with the microphone device driver: (Code taken from 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;

When the data buffers are full (?), the WasapiCapture raises the DataAvailable event to which the CaptureOnDataAvailable eventhandler is attached. In order to have the event handler, CaptureOnDataAvailable, update the UI, I've had to use the synchronizationContext:

synchronizationContext = SynchronizationContext.Current;

and then:

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);
        }

So, am I correct to assume that an event handler will be run on the same thread it is attached to?

TIA

Alan Wayne
  • 5,122
  • 10
  • 52
  • 95
  • 1
    *"am I correct to assume that an event handler will be run on the same thread it is attached to?"* No, you can not rely on that. The owner of the event may fire it in whatever thread it likes to. – Clemens Apr 12 '18 at 05:01
  • @Clemens Yes...but once fired, does the event handler run in the same thread as the event? – Alan Wayne Apr 12 '18 at 16:03
  • 1
    The event doesn't run by itself, only the handlers. And of course in the thread in which the event is fired. – Clemens Apr 12 '18 at 16:43

0 Answers0