【发布时间】:2011-12-01 17:26:46
【问题描述】:
我听说在 asp.net 中使用 ThreadPool 很糟糕,但是我将它用于自学。我的目标是确定 Application_Error 事件是否被触发(在 Global.asax 中处理) - 我对此的回答是:不,它不会被触发。
但我观察到了一些奇怪的事情。我编写的线程只是将任务排队到线程池。该任务旨在随机抛出错误。但是我观察到我经常收到错误 - 数字超过了数字。我已经将任务排队的次数。我有一个单独的问题是即使System.Diagnostics.Trace.WriteLine() 也没有将消息记录到我的输出窗口(Visual Studio)。为什么会有这种奇怪的行为?
using System;
using System.Threading;
namespace ThreadPoolDemo.Web
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(createthreads);
t.IsBackground = true;
t.Start();
}
void createthreads()
{
Thread.Sleep(10 * 1000);
int i;
System.Diagnostics.Trace.WriteLine("Queueing items");
for (i = 0; i < 1; i++)
ThreadPool.QueueUserWorkItem(new WaitCallback(ErrorTask), null);
System.Diagnostics.Trace.WriteLine("End Queueing items");
}
void ErrorTask(object obj)
{
Random generator = new Random();
int value = generator.Next(1);
if (value == 0)
throw new Exception("Sample exception thrown");
else
System.Diagnostics.Trace.WriteLine("Processed thread");
}
}
}
【问题讨论】:
标签: asp.net multithreading threadpool asp.net-4.0