用另一个线程显示/隐藏标签

时间:2015-03-25 10:37:48

标签: c# multithreading winforms

Someting在我的代码中不起作用所以我想问一下是否有人可以帮助我。到目前为止我有这个:

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);
    }

所以searchLabel是我想要显示/隐藏的标签。我试着在操作开始之前显示标签,并在完成后隐藏它。不知何故,它会在代码执行后显示(//某些代码需要时间)然后保持可见。如何正确编码?

2 个答案:

答案 0 :(得分:2)

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;
}

答案 1 :(得分:1)

您正在使用UI线程

//some code that needs time

会挂起UI线程所以不会重新绘制,你应该使用新的async / await东西

Task.Run可能不适合你的情况,但我需要更多地理解'某些代码'。

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;
}