【问题标题】:how do i wait till the thread complete its job then execute the next command c#?我如何等到线程完成其工作然后执行下一个命令 c#?
【发布时间】:2012-02-07 22:11:58
【问题描述】:

我有下面的代码(但不起作用)..我需要等到线程完成它的工作然后执行下一个命令

private void btnPaste_Click(object sender, EventArgs e)
    {
        if (copiedItems != null)
        {
            if (copy)
            {
                System.Threading.Thread thPASTE = new System.Threading.Thread(PasteFromCopy);
                thPASTE.Start(currAddress);
                lock (this)
                {
                    btnRefresh_Click(sender, e);
                }
            }
            else
            {
                System.Threading.Thread thPASTE = new System.Threading.Thread(PasteFromMove);
                thPASTE.Start(currAddress);
                lock (this)
                {
                    btnRefresh_Click(sender, e);
                }
            }
        }
    }

粘贴应该做一些代码,然后我应该刷新我显示的列表..我需要这样做,因为当我在线程中调用刷新时它对我不起作用
我该怎么做??

【问题讨论】:

  • 您可能还想考虑一个私有锁定变量,而不是锁定this。例如,private readonly object lockObject = new object();您可以查看此线程以了解更多详细信息stackoverflow.com/questions/251391/why-is-lockthis-bad
  • 启动一个线程然后等待它是没有意义的。你也可以直接调用 PasteFromCopy()

标签: c# multithreading synchronization wait


【解决方案1】:

您可以在线程实例上使用Join 方法,该方法将阻塞调用线程,直到另一个线程完成。

【讨论】:

    【解决方案2】:

    您也可以使用WaitHandlesWaitOneWaitAll 方法。

    【讨论】:

      【解决方案3】:

      i need to do it this way, because it doesn't work for me when i call the refresh in the thread

      您的问题与JoinWaitWaitOne 等线程同步无关。

      从 Windows 窗体中的辅助线程更新用户界面元素很棘手,因为不允许辅助线程直接从窗体或其任何子控件读取或写入属性值。存在此限制是因为 Windows 窗体中的窗体对象和控件对象不是线程安全的。唯一允许直接访问表单或其控件之一的属性值的线程是主 UI 线程

      要从线程(其他主线程)更新您的 GUI,您需要调用表单(或某些控件)的 InvokeBeginInvoke 方法将委托插入 UI 线程的调度程序。

      这些链接可以帮助您。

      How to update GUI from another thread in C#?

      Updating the UI from a Secondary Thread

      Updating the GUI from another thread made easy

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-17
        • 1970-01-01
        • 2019-10-29
        • 1970-01-01
        • 2022-11-24
        • 2016-07-14
        相关资源
        最近更新 更多