reason:
Some time -consuming operations block the main thread.
To understand the above reasons, you need to first understand the Winform thread mechanism. It mainly has the following two characteristics: 1. Single-threaded model; 2. Dependent on message loop.
1. Single thread model
Winform is a single thread by default. Generally, all UI operations, including control updates and event processing, are managed by the main thread (that is, UI thread).
Any code running within an event handler will tie up the main thread. If there is a time-consuming operation in an event, the thread will be blocked. For example, sometimes the display lags.
In the code below, the display of pictureBox1 will lag. The working principle behind this is:
After " = image0" is completed, the system only updates the Image property of pictureBox1, but does not trigger the drawing of the control immediately. (The actual drawing operation is handled by the message loop and is completed in the WM_PAINT message)
After the attribute settings of PictureBox1, if there is a time -consuming operation to occupy the UI thread, it will cause WM_Paint to be unable to handle it in time, so it cannot be drawn in time.
The best solution:
Avoid performing time-consuming tasks on the UI thread. You can ensure that the UI thread is always free to handle the message loop by moving time-consuming tasks to a background thread, such as using or async/await.
private void button2_Click(object sender, EventArgs e)
{
using (var session = new InferenceSession(_modelPath))
{
...... // irrelevant code
Bitmap image0 = new Bitmap(_imagePath);
= image0;
//The following is a time-consuming operation
DenseTensor<float> inputTensor = PreprocessImage(image0);
...
}
}
One additional point: only the main thread can access or update controls; if you want to access or update controls from other threads, and use specific inter-thread communication, you must use the or method to marshal the operation to the UI thread for execution. If you get a variable in the background thread and need to render it to the main interface, you need to use the wait method.
2. Rely on message loop
The UI thread depends on the MESSAGE LOOP processing and system messages of user input, punctuation clicks. When starting, the UI thread enters the message cycle state, constantly extract messages from the message queue and distributes to the corresponding control processing. The threads mentioned above are actually blocking the message cycle.
After the above two features are understood, the obstruction mentioned in the reason can be understood. If you don't understand, you can try to follow a simple time -consuming operation to help understand.