先看看CS类后面源码!public delegate void Treadmoden(int n);
public class Account
{
    public static int balance;
    private Treadmoden DLtread;
    Random random = new Random();
    public Account(int initial,Treadmoden tt)
    {
        balance = initial;
        DLtread = tt;
      //  HttpContext.Current.Response.Write("存款不足!");
    }     void withdraw(int amount)
    {        
        if (DLtread != null) DLtread(amount);
    }
    public void transactions()
    {for (int i=0;i<4;i++)
    withdraw(random.Next(1,500));
    }ASPX后台源码 public void readmoney(int money)
    {
        if (Account.balance < 0)
            Response.Write("存款不足");
        lock (this)
        {
         //  Thread.Sleep(100);//为什么这句话加上就不正确,出现Response.Write响应在此上下文中不可用!
         //在控制台的CS中就可以加上这句,不知为什么
           Response.Write(Thread.CurrentThread.Name.ToString() + " ");
            if (Account.balance >= money)
           {
               Response.Write("提前" + Account.balance.ToString());
              Response.Write("提了" + money.ToString());
               Account.balance = Account.balance - money;
              Response.Write("提后" + Account.balance.ToString()+"<br/>");
            }
           else
            { Response.Write("存款不足!" + Account.balance.ToString() + "<br/>"); }
        }
      
    }
    protected void Page_Load(object sender, EventArgs e)
    {
       
        Thread[] threads = new Thread[2];
        Account account = new Account(1000, new Treadmoden(readmoney));
        for (int i = 0; i < 2; i++)
        {
         threads[i] = new Thread(new ThreadStart(account.transactions));
            threads[i].Name = "thread"+i;
       }
       for (int i = 0; i < 2; i++)
         threads[i].Start(); 
        
    
    }

解决方案 »

  1.   

    HttpContext.Current.Response.Write(Thread.CurrentThread.Name.ToString() + " ");
      

  2.   

    哦,忘记了。线程委托是在页面加载完毕后还能执行的一种回调函数。在这里不能执行任何Response.Write
      

  3.   

    是不错,以上代码可以正常运行,
    运行结果如下
    thread0 提前1000提了154提后846
    thread0 提前846提了310提后536
    thread0 提前536提了116提后420
    thread0 提前420提了267提后153
    thread1 提前153提了70提后83
    thread1 存款不足!83
    thread1 存款不足!83
    thread1 存款不足!83
    但多了一个Thread.Sleep(100);就不对了
    有人提出线程异步,不知怎么用法!也不知可行否!
      

  4.   

    不明白,Page都执行完成了,Response给谁呢?
    在Page_Load执行完成后,用户已经看到页面了,此时你还能向他浏览器写东西?
      

  5.   

    服务器输出页面不会等你Sleep