从不同的班级访问后台工作人员

时间:2017-03-23 20:23:50

标签: c# visual-studio-2015 backgroundworker

我在Windows窗体应用程序中将逻辑从一个类分离到另一个类。当所有在一个班级中,它工作正常,但我现在正在将逻辑移动到它自己的各个班级。从另一个班级到backgroundWorker遇到一些问题。

我在A级

public partial class ClassA : Form
    BackgroundWorker essentialBgWorker = new BackgroundWorker();

    public ClassA()
        {
            InitializeComponent();
            //essentialBgWorker
            essentialBgWorker.DoWork += new DoWorkEventHandler(essentialBgWorker_DoWork);
            essentialBgWorker.ProgressChanged += new ProgressChangedEventHandler(essentialBgWorker_ProgressChanged);
            essentialBgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(essentialBgWorker_RunWorkerCompleted);
            essentialBgWorker.WorkerReportsProgress = true;
        }

这是一个带有按钮的表单,单击该按钮时,会将文件复制到另一个目录。

private void copyButton_Click(object sender, EventArgs e)
{
    clickedButton = ((Button)sender).Name.ToString();
    itemsChanged = ((Button)sender).Text.ToString();
    essentialBgWorker.RunWorkerAsync();
}

这会运行后台工作程序:

public void essentialBgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string buttonSender = clickedButton; //copyButton, deleteButton, etc.
    switch (buttonSender)
    {
        case "copyButton":
            //this is pseudocode - the important part being that this is where I would call the method from the other class
            ClassB.copyDocuments();
            break;
        case "deleteButton":
            //this is pseudocode - the important part being that this is where I would call the method from the other class
            ClassB.deleteDocuments();
            break;
        default:
            essentialBgWorker.CancelAsync();
            break;
    }
}

在我的另一个类(ClassB)中,对于此示例,我有单击按钮时调用的方法(应该处理逻辑)。

public void copyDocuments()
{
    ClassA classA = new ClassA();
    //
    //the logic that handles copying the files
    //gets the filecount!

    //Report to the background worker
    int totalFileCount = fileCount;
    int total = totalFileCount; //total things being transferred
    for (int i = 0; i <= total; i++) //report those numbers
    {
        System.Threading.Thread.Sleep(100);
        int percents = (i * 100) / total;
        classA.essentialBgWorker.ReportProgress(percents, i);

        //2 arguments:
        //1. procenteges (from 0 t0 100) - i do a calcumation 
        //2. some current value!
    }
    //Do the copying here
}

我一直有这条线的问题:

classA.essentialBgWorker.ReportProgress(percents, i);

ClassA中时,这一行有效 - 但是一旦将它带入ClassB就会出错:

ClassA.essentialBgWorker' is inaccessible due to it's protection level

只是寻找一些帮助,以正确的方式从其他班级开始。

1 个答案:

答案 0 :(得分:1)

您必须将public修饰符添加到essentialBgWorker

public BackgroundWorker essentialBgWorker = new BackgroundWorker();