C# 在 ASP.NET Web 应用程序中创建线程的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1824933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
right way to create thread in ASP.NET web application
提问by char m
i'm creating asmx web service and have to create thread to do background IO to refresh system data. What is the right way? I'm not interested to get any results to creating thread. I just want the ASP.NET worker thread to create a thread that does it's loading and in the end makes one assign (I think assign _alldata = newData is atomic where both instances of my own big structure class SystemData) so the worker thread that created the the new thread can propagate instantly.
我正在创建 asmx Web 服务,并且必须创建线程来执行后台 IO 以刷新系统数据。什么是正确的方法?我不想获得任何创建线程的结果。我只希望 ASP.NET 工作线程创建一个线程来加载它,最后进行一个分配(我认为assign _alldata = newData 是原子的,其中我自己的大结构类 SystemData 的两个实例都是原子的)所以创建的工作线程新线程可以立即传播。
I read an article http://msdn.microsoft.com/fi-fi/magazine/cc164128%28en-us%29.aspx#S2which suggest to use non-threadpool thread. The article however was about different / more complex scenario and didn't help me so much.
我读了一篇文章http://msdn.microsoft.com/fi-fi/magazine/cc164128%28en-us%29.aspx#S2建议使用非线程池线程。然而,这篇文章是关于不同/更复杂的场景,并没有给我太多帮助。
Thanks: Matti
谢谢:马蒂
PS. I have asked this question also in what is the right way to spawn thread for database IO in asmx web service?but that was too complex with multiple questions.
附注。我也问过这个问题,在 asmx Web 服务中为数据库 IO 生成线程的正确方法是什么?但这太复杂了,有多个问题。
采纳答案by RickNZ
Something like this:
像这样的东西:
public delegate void Worker();
private static Thread worker;
public static void Init(Worker work)
{
worker = new Thread(new ThreadStart(work));
worker.Start();
}
public static void Work()
{
// do stuff
}
Then get things started by calling Init(Work)
.
然后通过调用开始工作Init(Work)
。
If you call BeginInvoke()
or ThreadPool.QueueUserWorkItem()
, it uses an ASP.NET thread pool thread, which can impact the scalability of your application.
如果调用BeginInvoke()
或ThreadPool.QueueUserWorkItem()
,它将使用 ASP.NET 线程池线程,这会影响应用程序的可伸缩性。
In case it's useful, I cover these issues in detail in my book, along with code examples, sample benchmarks, etc: Ultra-Fast ASP.NET.
如果有用,我会在我的书中详细介绍这些问题,以及代码示例、示例基准测试等:超快速 ASP.NET。
回答by SirMoreno
Take a look at:
看一眼:
You can do something like:
您可以执行以下操作:
public delegate void MethodInvoker();
private void Foo()
{
// sleep for 10 seconds.
Thread.Sleep(10000);
}
protected void Button2_Click(object sender, EventArgs e)
{
// create a delegate of MethodInvoker poiting to
// our Foo function.
MethodInvoker simpleDelegate = new MethodInvoker(Foo);
// Calling Foo Async
simpleDelegate.BeginInvoke(null, null);
}