【发布时间】:2019-02-17 20:33:36
【问题描述】:
您好,我是多线程新手,想请教您的建议和指导。
我们的服务器上运行了一项服务,用于轮询数据以获取客户端的通知。我们希望该服务能够更快地处理数据。目前,我们现有的服务在单个线程上轮询和处理数据,这有时会导致每小时的通知延迟。我的计划是使用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。我做对了吗?想问一些关于我的概念的指导和优缺点。
【问题讨论】:
-
也许阅读“备注”部分并检查其中的要点:docs.microsoft.com/en-us/dotnet/api/…,还要检查 SetMaxThreads 的返回值。是
false吗? -
@MrinalKamboj;这在 .net 3.5 中可用吗?
-
@MrinalKamboj "从 .NET Framework 4 开始,TPL 是首选方式" Source OP 在 3.5
-
@Stefan 错过了那部分,是的,它从 .Net 4.0 开始
-
@JonathanDaniel:是的,ThreadPool 只是调节产生的线程数量。信号量就像一个保镖:它调节并发活动线程。注意:它通过等待来做到这一点,所以如果你触发 1300 个线程,并允许 3 个同时处于活动状态; 1297 将等待。
标签: c# multithreading windows-services threadpool