简体   繁体   English

C# 如何关闭用户窗体与工作线程

[英]C# how close userform with worker thread

I start new thread (worker) in userform, when this thread need something update in userform, then call Invoke method - invoke method delegate on main thread.我在用户窗体中启动新线程(工作者),当该线程需要在用户窗体中更新某些内容时,然后调用 Invoke 方法 - 在主线程上调用方法委托。 Problem is how successfully close userform.问题是如何成功关闭用户表单。 I need first time finish worker thread, from this thread is time for time called main thread (Invoke).我需要第一次完成工作线程,从这个线程开始是称为主线程(调用)的时间。 How in main thread wait until worker thread finish last loop.主线程如何等待工作线程完成最后一个循环。

Userform用户表单

  public partial class FormMain : Form
  {
    private bool isntSignaledStop=true;
    ...

Here is a loop method that runs on the worker thread.这是一个在工作线程上运行的循环方法。

private void MenuLoop()
{
  while (isntSignaledStop)
  {
    HeavyMethod();
    Invoke(DelegateWriteResultsToMenu);

    HeavyMethod2();
    Invoke(DelegateWriteResultsToMenu2);

    ...
  }
}

Main thread at end set isntSignaledStop=False.结束时的主线程设置 isntSignaledStop=False。 Now i need wait until worker thread is finished.现在我需要等到工作线程完成。

You can use async/await approach and use tasks instead of threads .您可以使用async/await方法并使用tasks而不是threads Redesign MenuLoop method to return a Task :重新设计MenuLoop方法以返回Task

private volatile bool isntSignaledStop = true;
private async void ButtonStart_Click(object sender, EventArgs e)
{
    await MenuLoop();
    Close();
}

private Task MenuLoop()
{
    return Task.Run(() =>
    {
        while (isntSignaledStop)
        {
            HeavyMethod();
            Invoke(DelegateWriteResultsToMenu);

            HeavyMethod();
            Invoke(DelegateWriteResultsToMenu);
        }
    });
}
private void ButtonStop_Click(object sender, EventArgs e)
{
    isntSignaledStop = false;
}

In the UI thread you can asynchronously wait until MenuLoop finishes the work and then close the window.在 UI 线程中,您可以异步等待MenuLoop完成工作,然后关闭窗口。

If you have MenuLoop running on "Thread2" (pretending that's the name), I'd call Thread2.Join() on your Main Thread, which will make the main thread wait until Thread2 is finished.如果您在“Thread2”上运行 MenuLoop(假装这是名称),我会在您的主线程上调用 Thread2.Join(),这将使主线程等待直到 Thread2 完成。

I'd recommend reading this post, it's got a really great answer with 5 different ways to do this.我建议阅读这篇文章,它有一个非常好的答案,有 5 种不同的方法来做到这一点。 How to wait for thread to finish with .NET? 如何等待线程完成.NET?

Hopefully this helps!希望这会有所帮助!

Thanks for the help, but I hope I found a way to do it with threads.感谢您的帮助,但我希望我找到了一种使用线程的方法。 Run main code on worker thread.在工作线程上运行主代码。 Because userform itself works as I need, it allows user input, or executes invoked method from another thread, and if it does nothing, then waiting...因为 userform 本身按我的需要工作,它允许用户输入,或者从另一个线程执行调用的方法,如果它什么都不做,那么等待......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM