C#中,创建子线程与Task任务相比,能够循环执行特定操作,可以用于长期监听TCP消息,发送心跳等。
本文对C#的多线程简单封装一下,哎,以方便线程的创建和命名。
using System.Threading;
/// <summary>
/// 创建进程的函数
/// </summary>
/// <param name="work">进程要执行的函数</param>
/// <param name="tName">进程的名称</param>
public delegate void WorkProc();
public static void CreateWorkThread(WorkProc work, string tName)
{
Thread thread = new Thread(new ThreadStart(work));
thread.Name = tName;
thread.IsBackground = true;
thread.Start();
}
CreateWorkThread(() =>
{
while (true)
{
try
{
// 要执行的代码
}
catch (Exception ex)
{
Console.WriteLine($"报错:{ex}");
}
}
}, "MyThread4Test");