0

I have a question about the System.Net.Sockets.NetworkingStream class (or the networking classes in general).

They have some asynchronous BeginX methods like BeginRead and (as far as I understand) they use a "background thread" to handle the method and you have to pass a callback method which is called when the method is "done" (for example when there is incoming data ready to read).

But what I don't understand yet: On which thread is the callback method running? Is it executed on the "main thread" which called the BeginRead method or are they executed on the "background thread" which was created by the BeginX method?

I need to know this, because I want to know if these callbacks are "thread safe" or if I could run into any threading issues with these if they are executed on a "background thread"

(Im using the BeginX methods instead of the "normal" methods, because I don't want to block my application)

R1PFake
  • 410
  • 2
  • 8
  • The callback will run on an "I/O thread". If you want more information about it, you can read this: https://stackoverflow.com/questions/2099947/simple-description-of-worker-and-i-o-threads-in-net But the important part is that your callback will run in parallel with your other code, so you have to handle thread safety where needed – Kevin Gosse Sep 22 '18 at 11:49
  • I see, thanks for the link! I guess then the only way to avoid the threading "problems"/safety would be to use the normal methods (which block) and put them in a "network update loop" and only call them if they have data (luckily they all have properties with this information). Now I just need to find a good way to put this "network loop" in my WPF app. – R1PFake Sep 22 '18 at 12:31
  • After some more reasearch I think (for my use case) it would be the easiest to use the blocking methods and "pool" the checks/calls in the WPF Dispatcher (similar to the prime number example) https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/threading-model But that's kinda off-topic your comment answerd my question, can you repost it as a answer, then I can accept it and close this question ;) – R1PFake Sep 22 '18 at 14:25
  • Let's just close it as duplicate, I didn't bring any new elements :) – Kevin Gosse Sep 22 '18 at 21:46

0 Answers0