知道另一个类中很长的函数(执行时间)的状态

时间:2012-09-05 12:45:28

标签: c# .net wpf visual-studio-2010

目前我有一个后台线程,其doWork调用类似于下面的函数。

private void ThreadForAnalyzingReqFile_DoWork(object sender, DoWorkEventArgs e) 
{
    AnotherClass.AVeryLongTimedFunction();
}

现在,代码应该等到另一个类中的 AVeryLongTimedFunction()结束(可能需要大约1-2分钟)当发生这种情况时,我怎么知道究竟是什么发生了什么?有什么方法可以通知我该功能(在另一个类中)完成了吗?

这个帖子在我的WPF的MainWindow类中。我正在使用Visual Studio 2010。

3 个答案:

答案 0 :(得分:0)

尝试将回调函数传递给“VeryLongTimedFunction”并在每次发生某种“进度”事件时调用它,例如每次处理50个项目,或者进行20次迭代,或者操作的情况如何

答案 1 :(得分:0)

有很多方法可以做到这一点。两个简单的选择:

(1)在您的UI类中创建一个事件,例如UpdateProgress,并以有意义的间隔通知该事件

示例:

    private void ThreadForAnalyzingReqFile_DoWork(object sender, DoWorkEventArgs e)
    {
        AnotherClass processor = new AnotherClass();
        processor.ProgressUpdate += new AnotherClass.ReallyLongProcessProgressHandler(this.Processor_ProgressUpdate);
        processor.AVeryLongTimedFunction();
    }

    private void Processor_ProgressUpdate(double percentComplete)
    {

        this.progressBar1.Invoke(new Action(delegate()
        {
            this.progressBar1.Value = (int)(100d*percentComplete); // Do all the ui thread updates here
        }));
    }

在“AnotherClass”中

public partial class AnotherClass
{
    public delegate void ReallyLongProcessProgressHandler(double percentComplete);

    public event ReallyLongProcessProgressHandler ProgressUpdate;

    private void UpdateProgress(double percent)
    {
        if (this.ProgressUpdate != null)
        {
            this.ProgressUpdate(percent);
        }
    }

    public void AVeryLongTimedFunction()
    {
        //Do something AWESOME
        List<Item> items = GetItemsToProcessFromSomewhere();
        for (int i = 0; i < items.Count; i++)
        {
            if (i % 50)
            {
               this.UpdateProgress(((double)i) / ((double)items.Count)
            }
            //Process item
        }
    }
}

(2)在AnotherClass上创建进度百分比字段。偶尔在计时器的UI中查询它。

答案 2 :(得分:0)

正如其他人所暗示的,有多种方法可以实现这一点,但最简单的方法似乎只是使用BackgroundWorker而不是线程。

要指示进度,只需将WorkerSupportsCancellation属性设置为true,然后调用worker.ReportProgress(percentage complete)以指示进度。对于完成通知使用事件通知,例如,

worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(method_run_on_complete);
private void method_run_on_complete(object sender, DoWorkEventArgs e) { ... }

有关详细信息,请参阅:

http://www.dreamincode.net/forums/topic/112547-using-the-backgroundworker-in-c%23/

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/28774446-144d-4716-bd1c-46f4bb26e016