如何在一个循环中更新文本框在C#另一个线程运行 [英] How update textbox in a loop running on another thread in C#

查看:251
本文介绍了如何在一个循环中更新文本框在C#另一个线程运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用后面的code在这样一个ASP应用程序更新一个文本框:

I am trying to update a textbox using the code behind in an ASP application like this:

    protected void click_handler(object sender, EventArgs e)
    {
        Thread worker = new Thread(new ThreadStart(thread_function));
        worker.Start(); 
    }
    protected void thread_function()
    {
            int i = 0;
            while(true)
            {
                Textbox.Text = i.ToString();
                i++;
            }
    }

文本框显示了第一次一个变量,但它不会在此之后更新的,我究竟做错了什么?我搜索,人们suggestin呼吁Textbox.Update或Textbox.Refresh,但我认为这些都是老,因为他们不存在了。

The textbox shows one variable the first time but it doesn't get updated after that, what am I doing wrong? I searched and people are suggestin calling Textbox.Update or Textbox.Refresh but I think these are old as they don't exist anymore.

感谢

推荐答案

您不能使用服务器端code以这种方式更新客户端的价值。无论如何,你似乎缺少某种停顿(例如Thread.sleep代码)作为目前你的循环会疯狂地一发不可收拾。

You can't use server side code to update client side values in this manner. Anyway, you seem to be missing some kind of pause (e.g. Thread.Sleep) as currently your loop will run wildly out of control.

您需要考虑的东西,如沿着使用客户端脚本(即JavaScript的)的setTimeout

You need to look into using client side scripting (I.e. JavaScript) along with something like setTimeout:

https://developer.mozilla.org/en/docs/网络/ API / window.setTimeout

下面是一个例子:
http://jsfiddle.net/PXN9K/

为穷人格式和略微慵懒命名/重构道歉,但我这样做是我的手机上。

Apologies for the poor formatting and slightly lazy naming/refactoring, but I'm doing this on my phone.

下面是从小提琴的code,这里复制为未来子孙。

Here's the code from the fiddle, copied here for future posterity.

var i = 0;

var updateTextbox =function()
{ document.getElementById('textbox').value = '' + i; }

var update = function() {

window.setTimeout(function() {
i++;
updateTextbox();
update();

}, 1000);

};

updateTextbox();
update();

这篇关于如何在一个循环中更新文本框在C#另一个线程运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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