后台的C#程序过程 [英] C# program processes in background

查看:84
本文介绍了后台的C#程序过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编写自己的套接字服务器(作为控制台应用程序),并且由于我是C#中的多线程新手,所以我开始想知道线程和后台任务.我找到了一些可能的线程替代方法,例如( BackgroundWorker ,但用于UI)或 Task ...

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...

我已经编写了一个过程,该过程定期在无尽的while循环中运行,在该过程中,它检查客户端是否仍处于连接状态.

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

由于我无法从Google搜索中获得意见,因此我想问,是否正在后台运行进程,例如我的客户端检查,通过 Thread 和无休止的循环,这是正确的方法,或者一些更好的方法呢?

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?

推荐答案

如果您定期进行操作,那么 Timer 是合适的.请注意,有几种替代方法,它们具有不同的行为.这样做的动机是使计时器定期运行,因此在阅读代码时,意图很明显.

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.

如果您正在处理其他线程中的项目,则 Thread 会循环遍历

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.

如果您想在后台运行一些一次性的过程密集型任务,则最适合使用 Task .这将使用来自线程池的线程,并在完成后返回线程.如果您要同时运行其他内容,这也很有用.

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.

如果您需要等待某些IO操作(例如磁盘或网络),则可以使用task + async/await.等待时将完全不使用任何线程.

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.

我可能不会使用BackgroundWorker.这是在Windows窗体时代完成的,大部分已被任务所取代.

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

这篇关于后台的C#程序过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆