【问题标题】:Threadreference.isalive = true but in the threads window its location is [In a sleep, wait or join]Threadreference.isalive = true 但在线程窗口中它的位置是[在睡眠中,等待或加入]
【发布时间】:2011-09-29 15:33:11
【问题描述】:

我有一个简单的函数,它使用模态表单启动一个线程,然后等待表单关闭。

private static bool GetSomeText()
    {
        Thread threadx = new Thread(GetSomeTextx);

        threadx.SetApartmentState(ApartmentState.STA);
        threadx.Start();

        int i = 0;
        const int secs = 6000;
        while (threadx.IsAlive && i < secs)
        {
            Thread.Sleep(1000);
            i++;
        }

        if (i >= secs) //timeout
        {
            try
            {
                threadx.Abort();
            }
            catch { }

            MessageBox.Show("Timeout etc.");
            return false;
        }
        else
        {
            return CheckText(Constants.inputedtext);
        }
    }

    private static void GetSomeTextx()
    {
        WindowWrapper window = new WindowWrapper(Fun.GetForegroundWindow());
        FormGetSomeText epa = new FormGetSomeText { displaytext=Constants.displaytext};
        epa.ShowDialog(window);
        Constants.inputedtext= epa.inputedtext;
    }

问题是在关闭窗口后线程退出 GetSomeTextx() 但仍处于边缘状态... 之后,如果我在“while (threadx.IsAlive && i 切换到线程它显示“没有可用的源”,然后单击“显示反汇编”显示“没有可用的反汇编”。

这段代码几乎是另一种情况的 1:1 副本(在另一个有 2 个文本框而不是 1 个)我必须以这种方式获取值并且它可以正常工作...

会是什么?

Postdata:已尝试在 GetSomeTextx 末尾添加 Thread.CurrentThread.Abort 但没有结果...

【问题讨论】:

  • 开启非托管调试并启用微软符号服务器。如果您无法弄清楚,请发布您现在获得的堆栈跟踪。

标签: c# winforms multithreading modal-dialog


【解决方案1】:

要等待线程完成,请调用Join:

private static bool GetSomeText()
{
    Thread threadx = new Thread(GetSomeTextx);

    threadx.SetApartmentState(ApartmentState.STA);
    threadx.Start();

    // Wait for thread to exit
    threadx.Join();

如果您想在超时时支持报告,请调用Join 重载,让您指定超时值。

【讨论】:

  • 具有讽刺意味的是,我在提出问题后后来尝试了这种方法并且它奏效了,但我想知道为什么一种可行的(如果有问题的)方法停止这样做......
猜你喜欢
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 2013-05-29
相关资源
最近更新 更多