等待调用方法完成?

时间:2015-02-22 18:19:27

标签: c# multithreading

我有类似恶魔功能的东西,它是在新线程上启动的,它是一个无限循环来检查条件,如果是真的它会更新文本框,它会在一段时间内缩短,所以,一次又一次。我用来更新文本框的功能是:

private static void pour(TextBox t, string s)
    {
        try
        {
            Form f = t.FindForm();
            if (t.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(pour);
                f.Invoke(d, new object[] { t, s });
            }
            else
            {
                if (t.Text == "") t.Text += s;
                else t.Text += Environment.NewLine + s;
                if (t.Text != "") { t.Select(t.Text.Count() - 2, 1); t.ScrollToCaret(); }
            }
        }
        catch { }
    }

问题是,恶魔将调用主线程并在文本框更新之前继续,因此调用pour几次,这导致文本框使用相同的文本更新几次,而不是一次。如何等待这个被调用的方法完成?

编辑: 这是恶魔的功能:

private void demon_drain(string name, int interval)
    {
        System.Threading.Thread drain = new System.Threading.Thread(() =>
        {
            try
            {
                while (true)
                {
                    try
                    {
                        TextBox t = new TextBox();
                        try
                        {
                            t = (TextBox)F.Controls[name];
                        }
                        catch { System.Threading.Thread.Sleep(interval); continue; }
                        if (Drain == null) { System.Threading.Thread.Sleep(interval); continue; }
                        if (Drain == t.Text) { System.Threading.Thread.Sleep(interval); continue; }
                        pour(t, Drain);
                        System.Threading.Thread.Sleep(interval); continue;
                    }
                    catch { System.Threading.Thread.Sleep(interval); continue; }
                }
            }
            catch { }
        });
        drain.IsBackground = true;
        drain.Start();
    }

当我在倾倒后设置断点时它工作正常,睡眠时间越短,更新就越多,因此我认为它不等待调用,实际上......

0 个答案:

没有答案
相关问题