Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
146 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...