【问题标题】:C#.net - How to alert program that the thread is finished (event driven)?C#.net - 如何提醒程序线程已完成(事件驱动)?
【发布时间】:2017-02-28 12:05:31
【问题描述】:

这是我班上的一个sn-p:

public bool start()
{
   Thread startThread = new Thread(this.ThreadDealer);
   startThread.Start();
   return _start;
}

在 ThreadDealer() 中,我将布尔变量“_start”设置为 false 或 true。我现在需要但似乎无法弄清楚的是在 ThreadDealer()-Thread 完成时提醒 start() 执行其返回语句的事件。

我用 AutoResetEvent 和 .WaitOne() 尝试了一些东西,但是因为我有一个 GUI 可以阻止所有内容,并且当它执行我需要它做的事情时(等待线程完成),如果它阻止我的 GUI 是没用的.

任何帮助将不胜感激。

【问题讨论】:

    标签: c# .net multithreading events


    【解决方案1】:

    您想要做的——在 UI 线程的方法中等待后台线程,但仍然允许 UI 响应——这是不可能的。您需要将代码分成两部分:一部分在后台线程启动(或并行)之前执行,另一部分在后台线程完成后运行。

    最简单的方法是使用BackgroundWorker class。它在工作完成后在 UI 线程 (RunWorkerCompleted) 中引发一个事件。这是一个例子:

    public void start()
    {
        var bw = new BackgroundWorker();
    
        // define the event handlers
        bw.DoWork += (sender, args) => {
            // do your lengthy stuff here -- this will happen in a separate thread
            ...
        };
        bw.RunWorkerCompleted += (sender, args) => {
            if (args.Error != null)  // if an exception occurred during DoWork,
                MessageBox.Show(args.Error.ToString());  // do your error handling here
    
            // Do whatever else you want to do after the work completed.
            // This happens in the main UI thread.
            ...
        };
    
        bw.RunWorkerAsync(); // starts the background worker
    
        // execution continues here in parallel to the background worker
    }
    

    【讨论】:

      【解决方案2】:

      只需提出一个事件。它将在错误的线程上运行,因此任何事件处理程序都必须在必要时通过编组调用来处理该问题以更新任何 UI。通过使用 Control.Begin/Invoke 或 Dispatcher.Begin/Invoke,具体取决于您使用的类库。

      或者使用 BackgroundWorker 类,它会自动完成。

      【讨论】:

        猜你喜欢
        • 2023-04-06
        • 2010-12-19
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        • 2015-06-25
        相关资源
        最近更新 更多