WebProject c#中的列表框和睡眠线程

本文关键字:线程 列表 WebProject | 更新日期: 2023-09-27 17:50:45

我有一个新的Web项目,在Default.aspx中有一个ListBox和一个Button:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Width="174px"></asp:ListBox>
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        <br />
        <br />
        <br />
        <br />
    </div>
    </form>
</body>
</html>

Default.aspx.cs下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ProvaSequenza
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            ListBox1.Items.Add("Start");
            ListBox1.DataBind();
            ListBox1.Items.Add("sleep");
            System.Threading.Thread.Sleep(10000);
            ListBox1.Items.Add("The End.");
        }
    }
}

当我运行项目时,我没有得到我所期望的:我期望在列表框中添加"Start",在"sleep"之后,然后是"The End"。相反,我先得到了"睡眠",然后添加了"开始"answers"结束"在一起…为什么?

WebProject c#中的列表框和睡眠线程

你需要明白你的c#代码是在服务器上执行的。服务器端代码生成html、javascript和css。浏览器下载并显示所有内容并执行javascript。所以你的代码是Thread。Sleep在服务器上执行,同时为页面生成html。

如果你想在用户机上执行一些代码,在浏览器中你必须使用Javascript。