C#.NET - 如何以提醒线程完成(事件驱动)计划? [英] C#.net - How to alert program that the thread is finished (event driven)?

查看:463
本文介绍了C#.NET - 如何以提醒线程完成(事件驱动)计划?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我班的一个片段:

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

在ThreadDealer()我设置的布尔变量_start,以或真或假。我现在需要的,但似乎无法找出是一个事件提醒的start()时ThreadDealer(),以执行其return语句 - 线程完成

In ThreadDealer() I'm setting the boolean variable "_start" to false or true. What I need now but can't seem to figure out is an event to alert start() to execute its return statement when the ThreadDealer()-Thread has finished.

我想的东西用的AutoResetEvent和.WaitOne(),但因为我有一个图形用户界面,只有几个街区的一切,虽然它做什么,我需要做的(等待线程来完成),它是无用的,如果它会阻止我的GUI

I tried something with an AutoResetEvent and .WaitOne() but since I have a GUI that just blocks everything and while it does what I need it to do (wait for the Thread to finish) it is useless if it blocks my GUI.

任何帮助将是非常美联社preciated。

Any help would be much appreciated.

推荐答案

你想要做什么 - 的等在UI线程的方法后台线程的,但仍然允许用户界面是响应 - 是不可能的。你需要分割你的code分成两部分:一开始之前执行(或平行)的后台线程,另一个运行后在后台线程完成

What you want to do -- wait for the background thread in a method of the UI thread but still allow the UI to be responsive -- is not possible. You need to split your code into two parts: One executed before starting (or parallel to) the background thread and the other one running after the background thread has finished.

最简单的方法是使用<一个href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx">BackgroundWorker类。它提出了在UI线程的事件( RunWorkerCompleted )的工作完成之后。这里有一个例子:

The easiest way is to use the BackgroundWorker class. It raises an event in the UI thread (RunWorkerCompleted) after its work is done. Here's an example:

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
}

这篇关于C#.NET - 如何以提醒线程完成(事件驱动)计划?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆