user983924
user983924

Reputation: 393

.net c++ timer_tick function does not work

I created a button to start the timer and the interval of timer is 1000. I added a timer_Tick() event handler but it is not working, I dont understand the reason.

Here is my code:

void button1_Click(...)
{
    this->timer->Start();
    for( int i = 0; i < 1000; i++ )
        Thread::Sleep(1000);
    this->timer->Stop();
}

void timer_Tick(...)
{
    this->textBox->Text = "njmk"; // only to handle while debugging but it is not handled
}

Note: I added this:

this->timer->Tick += gcnew System::EventHandler(this, &Form1::timer_Tick);

EDIT :

OK, I will try to explain my problem clearly. I have a main form and in the status strip I have a toolstripprogressbar.
When I click a button, a function will start parsing a file and the progress bar must show the progress of the function. So here is my code:

void button_click(...)
{
    this->progressBar->Visible = true;
    this->backGroundWorker->RunWorkerAsync();
}

void backGorundWorker_DoWork(...)
{
    this->timer->Start();
    ParseFunction(); // it takes about two minute
    this->timer->Stop();
}

void timer_Tick(...)
{
    this->bacGroundWorker->ReportProgress(5);
}

void backGroundWorker_ProgressChanged(...)
{
    this->progressBar->Value += e->ProgressPercentage();
}
void backGroundWorker_RunWorkerComplete(...)
{
    this->progressBar->Visible = false;
}

Upvotes: 1

Views: 384

Answers (2)

Nasreddine
Nasreddine

Reputation: 37838

It's not working because you're making the thread (UI thread) sleep for 1000 * 1000 milliseconds (~16 minutes):

void button1_Click(...)
{
    this->timer->Start();
    for( int i = 0; i < 1000; i++ )
        Thread::Sleep(1000);
    this->timer->Stop();
}

That's why it can't update the textbox content.

Upvotes: 0

Marco
Marco

Reputation: 57583

When you use this->textBox->Text = "njmk" in timer event, main thread should update textbox text; but you're making main thread to sleep, so it's not free to update textbox!!
Remember that UI objects are updated from main thread!
This is the reason for which we use multithread if we have to run long procedures and let our window to be redrawn and respond to user.

Upvotes: 1

Related Questions