-1

编辑:通过添加丢失的进度更改事件处理程序来解决。

我正在将 WPF VB.net 应用程序移植到 C#,并且遇到了后台工作人员的问题,该工作人员在不同的类中具有 DoWork 方法。我怀疑我没有正确投射后台工作人员,或者我可能需要一个处理程序?

vb 示例代码工作正常,进度条指示正确,C# 代码似乎触发 bw.RunWorkerAsync(); 方法,因为它报告为 IsBusy=True 但没有其他响应、进度或对外部类的调用(据我所知)。

这是一个 WPF 应用程序,问题在于用户控件试图从控件外部的公共类报告进度。

如果有人能指出我正确的方向,我将不胜感激。

C# 示例代码

 namespace testApp.Usercontrols
    public partial class ucHome : UserControl
    {
        public Sharing.clsDownloadCollection foo = new Sharing.clsDownloadCollection(); 
         BackgroundWorker bw = new BackgroundWorker();



     public ucHome()         
{       InitializeComponent();
 }

private void Button1_Click(object sender, RoutedEventArgs e)
    {


        bw.WorkerReportsProgress = true;
        pBar.Maximum = 50000;   //progress bar on ucHome
        pBar.Value = 0;

        **// Indicates IsBusy=True when debugging but can't see any further activity
         bw.RunWorkerAsync();
        //**

    }

 public void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
          var foo=new foo();

         // possible problem?
           foo.DoWork((BackgroundWorker)sender);

        }

        public void bw_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {

            this.pBar.Value = e.ProgressPercentage;
        }

外部类不同的项目文件夹/命名空间

 namespace testApp.Sharing
{
//different namespace /folder than ucHome
 public class foo 

{
public void DoWork(BackgroundWorker bw)
{
    for (int i = 0; i <= 50000; i++) {
        i += 1;

        bw.ReportProgress(i - 1);
}
}

}

按预期工作的示例 VB 代码。

    Public Class ucHome 'user control
Public foo As New foo
Friend WithEvents bw As New BackgroundWorker
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        bw.WorkerReportsProgress = True  
        pBar.Maximum = 50000
        pBar.Value = 0
        bw.RunWorkerAsync() 

    End Sub
    Private Sub bw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
          'possible my C# is not casting correctly?
        foo.DoWork(DirectCast(sender, BackgroundWorker)) 

    End Sub

    Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bw.ProgressChanged
       Me.pBar.Value = e.ProgressPercentage
    End Sub

End Class

用户控件调用的类 foo

Public Class foo

  Public Sub DoWork(ByVal bw As BackgroundWorker)
        For i As Integer = 0 To 50000
            i += 1
         bw.ReportProgress(i - 1)
        Next
    End Sub
End Class
4

1 回答 1

0

通过添加缺少的后台程序 ProgressChanged 事件处理程序来解决。

于 2012-07-24T05:07:50.730 回答