Search code examples
c#winformslong-running-processes

Display loading message until complete SQL data retrieve


I'm using WeifenLuo dockpanel-suit.

I need to show some kind of splash form or loading message before SQL complets loading data.

What I've tried didn't work

  public partial class frmPostventa : DockContent
    {
       private void frmPostventa_Load(object sender, EventArgs e)
        {   

            bool done = false;
            ThreadPool.QueueUserWorkItem((x) =>
            {
                using (var splashForm = new SplashForm())
                {
                    splashForm.Show();
                while (!done)
                    Application.DoEvents();
                splashForm.Close();
            }
        });
        //Database task heavy load
        cargarDatos();
        done = true;

    }

    public void cargarDatos()
    {

        string strSQL = "exec SAI_ALGO.spPostventa";

        SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

        // Populate a new data table and bind it to the BindingSource.
        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;
        dataAdapter.Fill(table);
        bindingSource1.DataSource = table;

    }


}

EDIT: Added CargarDatos()


Solution

  • DoEvents() nearly always leads to a very bad place, and should pretty much always be avoided. The problem with this particular implementation is that your long running process (cargarDatos()) is going to block the UI thread until it completes, so DoEvents() will have no effect; it will not interrupt a method while it is executing (assuming cargarDatos() isn't doing something internally that would yield the thread). Also, creating and interacting with a UI control from some background thread is not valid here.

    You should use a BackgroundWorker to perform the long running operation and raise status updates to the UI: http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx