-1

I'm currently writing my own socket server (as the console app), and as I am new to multithreading in C# I started wondering about threading and backgrounds tasks. I found some possible alternatives to Threads like (BackgroundWorker, but for UI) or Task...

I have currenctly written a process, which periodically runs in endless while loop, where its checking clients if they are still connected.

As I cannot get opinion from searching on google, so I'm asking, is running processes in background, like my client check, through the Thread and endless loop a proper way, or there are some better ways how to do it?

Zechy
  • 45
  • 12
  • [Asynchronous socket server example](https://learn.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example) – John Wu May 13 '20 at 07:26
  • 1
    There will always be a thread (at least on Windows). All the things you describe are abstractions over the OS supplied Thread. – rene May 13 '20 at 07:33
  • @JohnWu Well, that's all around accepting connection, listening to connection... I'm wondering more about process, which si checking if `Socket.Connected` is `true`. But prior to comment by **rene**, I have suitable answer. – Zechy May 13 '20 at 07:49
  • @rene That's suitable answer. – Zechy May 13 '20 at 07:50
  • @rene And what about some processes which has to run only after some period of time? I was [asking yesterday](https://stackoverflow.com/questions/61727572/socket-server-and-nunit-thread-sleep), now I have solution from the comment. But isn't there something like in JS setInterval()? – Zechy May 13 '20 at 07:53

1 Answers1

1

If you are doing things periodically then a Timer would be suitable. Note that there are several alternatives with different behaviors. The motivation is that timers are made to run things periodically, so the intent becomes obvious when reading the code.

If you are processing items from other threads a Thread looping over a blocking collection is suitable. This can me useful if the processing needs to be in-order or singlethreaded. This will lockup some resources for the thread, so should be used somewhat sparingly.

If you want to run some one-off process-intensive task(s) in the background then a Task is most appropriate. This will use a thread from the threadpool, and return the thread when done. This is also useful if you want to run different things concurrently.

If you need to wait for some IO operation, like disk or network, then tasks + async/await is appropriate. This will not use any thread at all when waiting.

If running some process-intensive work in parallel, then Parallel.For/Foreach is suitable.

I would probably not use BackgroundWorker. This was made during the windows forms era, and is mostly superseded by tasks.

JonasH
  • 28,608
  • 2
  • 10
  • 23