你好,我是一名新手,对多线程不太了解,希望能请教您的建议和指导。
我们在服务器上运行一个服务,用于为客户端轮询数据以进行通知。我们希望该服务能够更快地处理数据。目前,我们现有的服务在单个线程上轮询并处理数据,这有时会导致每小时通知的延迟。我的计划是使用ThreadPool
来实现并发处理数据。我有以下代码可以模拟我的计划和想法。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security;
using System.Text;
using System.Threading;
using System.Xml;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Web;
namespace ThreadPooling
{
class Program
{
static int nMaxRecord = 0;
static ManualResetEvent mre = new ManualResetEvent(false);
static Timer TestThread = null;
static void Main(string[] args)
{
TestThread = new Timer(new TimerCallback(ProcessWithThreadPoolMethod), null, 500, Timeout.Infinite);
Thread.Sleep(Timeout.Infinite);
}
static void ProcessWithThreadPoolMethod(object ostate) // Sample processing of data
{
nMaxRecord = 1300;
ThreadPool.SetMaxThreads(3, 0);
for (int i = 0; i < 1300; i++)
{
ThreadPool.QueueUserWorkItem(ProcessWithThreadMethod, i);
}
mre.WaitOne();
Console.WriteLine("Test");
TestThread.Change(5000, Timeout.Infinite);
}
static void ProcessWithThreadMethod(object callback)
{
for (int i = 0; i <= 10; i++)
{
Console.WriteLine((int)callback);
}
if(Interlocked.Decrement(ref nMaxRecord) == 0)
{
mre.Set();
}
}
}
}
在运行控制台应用程序时,我注意到线程计数不断增加,尽管我通过ThreadPool
将最大线程数限制为3。这样做是否正确?想要一些指导并了解我的思路的优缺点。