Loading image stops issue

南楼画角 提交于 2019-12-10 17:25:20

问题


I have windows form. I have put one loading image in PictureBox

When I load form then I have set

PictureBox1.Visible = false;

While i am firing click event of button I have set

PictureBox1.Visible = true;

But in that event there is some code to retrieve data from database through stored procedure.

When it will jump to code for retrieving data from stored procedure that loading image stops to load.

It should not be happened. It should show as loading. I have used .gif loading image.

How can I solve this issue ?


回答1:


Everytime you have a long lasting call within an eventHandler you should use a BackgroundWorker! A BackgroundWorker can run code async and therefor your button_click eventHandler will end right after starting the worker.

// add a BackGroundWorker bwLoadData to your form

private void YOURBUTTON_Click(object sender, EventArgs e)
{
     PictureBox1.Visible = true;
     bwLoadData.RunWorkerAsync();
}
private void bwLoadData_DoWork(object sender, DoWorkEventArgs e)
{
     // access your db, execute storedProcedue and store result to
     e.Result = YOUR_DATASET_RECORDS_OR_ANYTHING_ELSE;
}
private void bwLoadData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     if (e.Result != null)
     {
          // e.g. show data on form
     } else {
          // e.g. error message
     }
}



回答2:


Most probably, while you are running the stored procedure, the UI thread is blocked. You may use a BackGroundWorker in order to fetch data from database, which creates another thread and does not block your main thread.

Or you may create a thread manually and use it to retrieve data from database. In windows forms, as a best practice, it is better to use another thread for running external system calls in order not to block UI thread.

backgroundworker usage




回答3:


The possible reason for this might be sharing of same thread by loading image and data retrieval. So, you might try with multithreading or async calls to get data . Sorry for the previous answer about ajax / javascipt web worker, I completely neglected u mentioned windows form.



来源:https://stackoverflow.com/questions/12103884/loading-image-stops-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!