Reputation:
Someting doesn't work in my code so I wanted to ask if someone can help me. I have this so far:
private void searchList_TextChanged(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(setLabel));
th.IsBackground = true;
th.Start();
//some code that needs time
if (searchBox.Text == String.Empty)
{
listViewType.Items.Clear();
fillListView();
}
else
{
listViewType.Items.Clear();
var matchings = stringTypes.FindAll(delegate(string s) { return s.StartsWith(searchBox.Text); });
for (int i = 0; i < matchings.Count; i++)
{
ListViewItem storeMatched = new ListViewItem(matchings[i]);
storeMatched.SubItems.Add(matchings[i]);
listViewType.Items.Add(storeMatched);
}
th.Abort();
searchLabel.Visible = false;
}
private void setLabel()
{
MethodInvoker set = () => searchLabel.Visible = true;
searchLabel.BeginInvoke(set);
}
So searchLabel is a label that I want to show/hide. I tried here to show the label before the operation begins and hide it after it finished. Somehow it gets shown AFTER the code was executed (//some code that needs time) and then stays visible. How to code that correctly?
Upvotes: 0
Views: 1412
Reputation: 2048
You are doing work on the UI thread
Your
//some code that needs time
Will hang the UI thread so will not re-draw, you should use the new async / await stuff
Task.Run might not be right for your case but I would need to understand the 'some code' more.
private async void searchList_TextChanged(object sender, EventArgs e)
{
searchLabel.Visible = true;
await Task.Run(() =>
{
// code that needs time
});
// simulate
await Task.Delay(5000);
searchLabel.Visible = false;
}
Upvotes: 1
Reputation: 3476
private void searchList_TextChanged(object sender, EventArgs e)
{
searchLabel.Visible = false;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//some code that needs time
Thread.Sleep(1000);
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
SetLabelVisible(true);
}
private delegate void SetLabelVisibleDelegate(bool status);
private void SetLabelVisible(bool status)
{
if (searchLabel.InvokeRequired)
searchLabel.Invoke(new SetLabelVisibleDelegate(SetLabelVisible), status);
else
searchLabel.Visible = status;
}
Upvotes: 2