如何使用线程在asp.net? [英] How to use threads in asp.net?
问题描述
我有Web窗体应用程序。在一个形式,我有几个功能。这被称为syncronously并需要一些时间。所以,我要叫他们在不同的线程。
I have web forms application. On one form I have a few functions. Which are called syncronously and takes some time. So I need to call them in different threads.
这是我在做什么的示例:
This is the sample of what I'm doing:
protected void Page_Load(object sender, EventArgs e)
{
Thread t1 = new Thread(new ThreadStart(Function1));
t1.Start();
Thread t2 = new Thread(new ThreadStart(Function2));
t2.Start();
}
private void Function1()
{
Thread.Sleep(5000);
lbl1.Text = "Function1 completed";
}
private void Function2()
{
Thread.Sleep(5000);
lbl2.Text = "Function2 completed";
}
如果我调试(集breackpoints) lbl1.Text =FUNCTION1完成;
和 lbl2.Text =功能2完成;
获取调用,但文本没有改变最终的HTML页面上。
If I debug (set breackpoints) lbl1.Text = "Function1 completed";
and lbl2.Text = "Function2 completed";
is getting called, but there texts are not changing on final html page.
此外页面加载并不需要5秒。
Also Page load does not takes 5 sec.
P.S。我知道ASP网的作品不同,但我不知道我做错了。
p.s. I know asp net works different but I have no idea what I'm doing wrong.
推荐答案
没有正在等待你的线程来完成网页渲染,并返回之前 - 这有什么不对。
Nothing is waiting for your threads to complete before the page is rendered and returned - that's what's wrong.
要你的的Page_Load()
函数的结束(或在页面渲染生命周期中的最新的,可能的点),地址:
To the end of your Page_Load()
function (or at the latest-possible point in the page rendering lifecycle), add:
t1.Join();
t2.Join();
此外:你不应该更新线程PROC内LBL1和LBL2 - 你应该存储在变量的结果(S),反映在主渲染线程的计算值(即一旦加入
返回)。
Additionally: you should not update lbl1 and lbl2 within the thread proc - you should store the result(s) in variables and reflect the calculated values in the main rendering thread (i.e. once Join
has returned).
编辑:虽然这修复了这个问题的问题,看看 PageAsyncTask 所推荐的瓦诺的回答。
Although this fixes the problem in the question, have a look at PageAsyncTask as recommended by Vano's answer.
这篇关于如何使用线程在asp.net?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!