What's the best way to asynchronously load dat

2019-07-23 05:36发布

问题:

This code allows the form to load before the data is loaded but some of the components on the form such as buttons and the datagridview itself are "invisible" until the data is loaded.

How do I fix this problem?

    private void Form1_Load(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(delegate()
        {
            this.Invoke(new MyDelegate(delegate()
            {               
                ReadXml(path);
                Bind();
           }));              
        }));

        t.Start();
     }

    private void Bind()
    {
        dataGridView1.DataSource = table;
    }

I also have this other code which works better, but requires that I use 2 new threads. This can't be the best way to do this, can it?

    private void Form1_Load(object sender, EventArgs e)
    {
        Thread t = new Thread(new ThreadStart(delegate()
          {
              this.Invoke(new InvokeDelegate(delegate()
              {
                  Thread t2 = new Thread(new ThreadStart(delegate()
                  {
                      ReadXml(path);
                  }));
                  t2.Start();
                  t2.Join();
                  Bind();
              }));
          }));

        t.Start();
    }

回答1:

If you use BeginInvoke() instead of an Invoke() the code in the delegate will be executed on the current UI thread but it wont happen until after all the current UI work pending finishes (like the current Form1_Load invocation). Invoke is a synchronous call so that's why you needed the thread.

   void Form1_Load(object sender, EventArgs e)
    {
        this.BeginInvoke(new MyDelegate(delegate()
        {
            ReadXml(path);
            Bind();
        }));
    }


回答2:

A form timer (not system timer) will let all other messages process before it fires.

Just give it an interval of like 100-250 milliseconds; Set it to enabled=false in the designer; Set it to enabled=true in the form_load event. In the timer_tick event make the first line timer.enabled = false. After that (still in the tick event) load your grid.



标签: c# .net xml forms