📄 form1.cs
字号:
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(608, 382);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.spinConsumingTime);
this.Controls.Add(this.label6);
this.Controls.Add(this.spinInterval);
this.Controls.Add(this.spinIdleTimeout);
this.Controls.Add(this.spinMaxThreads);
this.Controls.Add(this.spinMinThreads);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.btnStart);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(616, 416);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Test Smart Thread Pool";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.spinIdleTimeout)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinMaxThreads)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinMinThreads)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinInterval)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.spinConsumingTime)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pcActiveThreads)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pcInUseThreads)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pcQueuedWorkItems)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pcCompletedWorkItems)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool runApplication = InitializePerformanceCounters();
if (!runApplication)
{
return;
}
Application.Run(new Form1());
}
// This method is a work around for the Peformance Counter issue.
// When the first SmartThreadPool is created with a Peformance
// Counter name on a machine, it creates the SmartThreadPool
// Peformance Counter category. In this demo I use thes Performance
// Counters to update the GUI.
// The issue is that if this demo runs for the first time on the
// machine, it creates the Peformance Counter category and then
// uses it.
// I don't know why, but every time the demo runs for the first
// time on a machine, it fails to connect to the Peformance Counters,
// because it can't find the Peformance Counter category.
// The work around is to check if the category exists, and if not
// create a SmartThreadPool instance that will create the category.
// After that I spawn another process that runs the demo.
// I tried the another work around and thats to check for the category
// existance, run a second process that will create the category,
// and then continue with the first process, but it doesn't work.
// Thank you for reading the whole comment. If you have another way
// to solve this issue please contact me: amibar@gmail.com.
private static bool InitializePerformanceCounters()
{
if (!PerformanceCounterCategory.Exists("SmartThreadPool"))
{
STPStartInfo stpStartInfo = new STPStartInfo();
stpStartInfo.PerformanceCounterInstanceName = "Test SmartThreadPool";
SmartThreadPool stp = new SmartThreadPool(stpStartInfo);
stp.Shutdown();
if (!PerformanceCounterCategory.Exists("SmartThreadPool"))
{
MessageBox.Show("Failed to create Performance Counters.", "Test Smart Thread Pool", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Process process = new Process();
process.StartInfo.FileName = Application.ExecutablePath;
try
{
process.Start();
}
catch(Exception e)
{
e.GetHashCode();
MessageBox.Show("If this is the first time you get this message,\r\nplease try to run the demo again.", "Test Smart Thread Pool");
}
return false;
}
return true;
}
private Thread workItemsProducerThread;
private void btnStart_Click(object sender, System.EventArgs e)
{
UpdateControls(true);
workItemsCompleted = 0;
workItemsGenerated = 0;
STPStartInfo stpStartInfo = new STPStartInfo();
stpStartInfo.IdleTimeout = Convert.ToInt32(spinIdleTimeout.Value)*1000;
stpStartInfo.MaxWorkerThreads = Convert.ToInt32(spinMaxThreads.Value);
stpStartInfo.MinWorkerThreads = Convert.ToInt32(spinMinThreads.Value);
stpStartInfo.PerformanceCounterInstanceName = "Test SmartThreadPool";
_smartThreadPool = new SmartThreadPool(stpStartInfo);
//_workItemsGroup = _smartThreadPool.CreateWorkItemsGroup(1);
_workItemsGroup = _smartThreadPool;
workItemsProducerThread = new Thread(new ThreadStart(this.WorkItemsProducer));
workItemsProducerThread.IsBackground = true;
workItemsProducerThread.Start();
}
private void btnStop_Click(object sender, System.EventArgs e)
{
running = false;
workItemsProducerThread.Join();
_smartThreadPool.Shutdown();
_smartThreadPool.Dispose();
_smartThreadPool = null;
GC.Collect();
GC.WaitForPendingFinalizers();
UpdateControls(false);
}
private void Form1_Load(object sender, System.EventArgs e)
{
UpdateControls(false);
}
private void UpdateControls(bool start)
{
running = start;
spinMinThreads.Enabled = !start;
spinMaxThreads.Enabled = !start;
spinIdleTimeout.Enabled = !start;
btnStart.Enabled = !start;
btnStop.Enabled = start;
timerPoll.Enabled = start;
lblThreadInUse.Text = "0";
lblThreadsInPool.Text = "0";
lblWaitingCallbacks.Text = "0";
usageThreadsInPool.Maximum = Convert.ToInt32(spinMaxThreads.Value);
usageThreadsInPool.Value1 = 0;
usageThreadsInPool.Value2 = 0;
lblWorkItemsCompleted.Text = "0";
lblWorkItemsGenerated.Text = "0";
usageHistorySTP.Reset();
usageHistorySTP.Maximum = usageThreadsInPool.Maximum;
}
private void spinMinThreads_ValueChanged(object sender, System.EventArgs e)
{
if (spinMinThreads.Value > spinMaxThreads.Value)
{
spinMaxThreads.Value = spinMinThreads.Value;
}
}
private void spinMaxThreads_ValueChanged(object sender, System.EventArgs e)
{
if (spinMaxThreads.Value < spinMinThreads.Value)
{
spinMinThreads.Value = spinMaxThreads.Value;
}
usageThreadsInPool.Maximum = Convert.ToInt32(spinMaxThreads.Value);
}
private void timer1_Tick(object sender, System.EventArgs e)
{
SmartThreadPool stp = _smartThreadPool;
if (null == stp)
{
return;
}
int threadsInUse = (int)pcInUseThreads.NextValue();
int threadsInPool = (int)pcActiveThreads.NextValue();
lblThreadInUse.Text = threadsInUse.ToString();
lblThreadsInPool.Text = threadsInPool.ToString();
lblWaitingCallbacks.Text = pcQueuedWorkItems.NextValue().ToString(); //stp.WaitingCallbacks.ToString();
usageThreadsInPool.Value1 = threadsInUse;
usageThreadsInPool.Value2 = threadsInPool;
lblWorkItemsCompleted.Text = pcCompletedWorkItems.NextValue().ToString();
lblWorkItemsGenerated.Text = workItemsGenerated.ToString();
usageHistorySTP.AddValues(threadsInUse, threadsInPool);
}
private void WorkItemsProducer()
{
WorkItemCallback workItemCallback = new WorkItemCallback(this.DoWork);
while(running)
{
IWorkItemsGroup workItemsGroup = _workItemsGroup;
if (null == workItemsGroup)
{
return;
}
try
{
workItemCallback = new WorkItemCallback(this.DoWork);
workItemsGroup.QueueWorkItem(workItemCallback);
}
catch(ObjectDisposedException e)
{
e.GetHashCode();
break;
}
workItemsGenerated++;
Thread.Sleep(Convert.ToInt32(spinInterval.Value));
}
}
private object DoWork(object obj)
{
Thread.Sleep(Convert.ToInt32(spinConsumingTime.Value));
Interlocked.Increment(ref workItemsCompleted);
return null;
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (null != _smartThreadPool)
{
_smartThreadPool.Shutdown();
_smartThreadPool = null;
_workItemsGroup = null;
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -