我是多线程的新手,想请教您的建议和指导。
我们在我们的服务器上运行了一项服务来轮询数据以获取我们客户的通知。我们希望该服务能够更快地处理数据。目前,我们现有的服务在单个线程上轮询和处理数据,这有时会导致每小时的通知延迟。我的计划是使用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();
}
}
}
}
在运行控制台应用程序时,我注意到线程数一直在增加,尽管我将 maxthreads 限制在ThreadPool3 以内。我做对了吗?想对我的概念提出一些指导和利弊。
GCT1015
MYYA
动漫人物
随时随地看视频慕课网APP
相关分类