如何在asp.net中使用线程? [英] How to use threads in asp.net?

查看:20
本文介绍了如何在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.

这是我正在做的示例:

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

如果我调试(设置断点)lbl1.Text = "Function1 completed";lbl2.Text = "Function2 Completed"; 被调用,但有文本在最终的 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.

附言我知道 asp net 的工作方式不同,但我不知道我做错了什么.

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();

此外:您不应该在线程过程中更新 lbl1 和 lbl2 - 您应该将结果存储在变量中并反映主渲染线程中的计算值(即一旦 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).

虽然这解决了问题中的问题,请查看PageAsyncTask 按照 Vano 的回答推荐.

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

这篇关于如何在asp.net中使用线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆