Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How update textbox in a loop running on another thread in C#

Tags:

c#

asp.net

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

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.

Thanks

like image 604
Shahab78 Avatar asked Mar 14 '14 18:03

Shahab78


1 Answers

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.

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

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

Here's an example: http://jsfiddle.net/PXN9K/

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

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();
like image 108
Ian Newson Avatar answered Oct 03 '22 07:10

Ian Newson