开发者

Visual Studio C++ How to get the Form not freezing while calling a time-consuming function?

开发者 https://www.devze.com 2023-03-09 23:34 出处:网络
I am making a C++/CLI Forms application. In the main window of my app I have a button. When I click that button I call the Load function. Below there is the C++/CLI code:

I am making a C++/CLI Forms application.

In the main window of my app I have a button. When I click that button I call the Load function. Below there is the C++/CLI code:

private: System::Void Button1_Click(System::Obje开发者_开发知识库ct^  sender, System::EventArgs^  e) {
     Load();
}

The function Load() is a time-consuming function. It uses the cURL library to send several HTTP GET request to a website.

In the Form I also included a ProgressBar and a textLabel showing the current request being sended.

The problem is that when I click the button and call the function the Form just freezes. I can't see the progressBar and Textlabel changing it's value while the function Load() is called, the Form is just freezed. When the function Load() has finished sending request, suddenly the progressBar change It's value to 100%.

I hope I described my problem clearly enough to understand it.


Move your task to another thread, or call Application.DoEvents();, just after you updating your scrollbar value.


Either break the task into smaller parts (design a finite state machine or use continuations) or use a separate thread.

The first approach takes more getting used to, but it's easier for an experienced programmer to get right. Threading requires synchronization which is very detail-oriented and causes a lot of hidden sporadic bugs which are extremely difficult to debug.


Call Form1.Refresh() every time you update an element of the form (say Form1). It will show the results immediately.


Before any line command that make probably any load time ...Write This:

System::Windows::Forms::Application::DoEvents();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号