Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

c# - How to use threads in asp.net?

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";
    }

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.

Also Page load does not takes 5 sec.

p.s. I know asp net works different but I have no idea what I'm doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Nothing is waiting for your threads to complete before the page is rendered and returned - that's what's wrong.

To the end of your Page_Load() function (or at the latest-possible point in the page rendering lifecycle), add:

t1.Join();
t2.Join();

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).

Edit: Although this fixes the problem in the question, have a look at PageAsyncTask as recommended by Vano's answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...