How to ensure the GUI elements and loaded before proceeding in C#
I am a beginner to C#. I am trying to make a simple program that displays the links from a website into a ListBox. Since retrieving the links takes time, my GUI waits till all the links are parsed and ListBox populated before it becomes visible.
I would assume that this is because the InitializeComponent() and my ParseLinks() methods run in the same thread. I would like to know if there is way I could run ParseLinks() after the UI elements are loaded.
public mainForm()
{
InitializeComponent();
ParseLinks();
}
I would appreciate any input. Thanks
[Edit]
More info on ParseLinks()
: (I am giving th开发者_如何学编程e summary since the code is quite extensive)
ParseLinks()
gets the links into an arraylist and assigns the arraylist to the ListBox
. The whole operation works very well. But I wanted the GUI to be displayed and then the ListBox
populated. I am also disabling a Button while at it and also changing a ProgressBar
Style to Marquee
. Referring to the response I gave below, when I used Backgroundworker
, I got multiple cross-thread operation error which I solved by placing the GUI editing code inside one InvokeRequired
statement
If you are using WinForms, I suggest using BackgroundWorker. Your form would populate ListBox in a background thread.
More details here and here.
[Edit]
Here is the basic idea:
public Form1()
{
InitializeComponent();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for(var i = 0; i < 1000; i++)
{
var newElement = BuildMyElement(i);
backgroundWorker1.ReportProgress(0, newElement);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var newElement = (MyType)e.UserState;
listBox1.Items.Add(newElement);
}
Replace backgroundWorker1_DoWork with the code that you use to retrieve URLs.
Put in the on form load function.
精彩评论