C#让代表可以上课

时间:2009-08-20 20:10:36

标签: c# visual-studio-2008 delegates scope backgroundworker

我想让整个班级都有代表。这一点的关键是允许来自外部类backgroundWorker的被调用方法不断地通过它的所有方法报告(ExternalClass.Run();调用ExternalClass.Method2(); ExternalClass.Method3();等等它们都需要发送几个进度报告。必须不断传递代表似乎效率低下。

我尝试全局初始化委托实例并将其设置为等于Run()中传递的实例;对于每个方法,然后可用,但我得到一个错误,无法隐式转换null对象。

谢谢!

我无法显示我正在使用的代码,因为我现在没有它(它在我的笔记本电脑上)但我现在会尝试更好地解释。伪代码:

class form1 : form {
    backgroundWorker_doWork()
    {
        Class2.Run();
    }

    backgroundWorker_OnProgressChange()
    {
         // do this
    }

}


class class2{
     Run(){
     OtherMethod();ThirdMethod();
     }

     OtherMethod(){ //need to call backgroundWorker.ReportProcess(int, string)}
     ThirdMethod(){ //need to call backgroundWorker.ReportProcess(int, string)}
} 

我真的不想每次都要传递它,我想以某种方式将它传递给class2

2 个答案:

答案 0 :(得分:4)

您应该显示无效的代码和完全错误消息。它应该没问题 - 这是一个例子:

using System;

class Demo
{
    private readonly Action action;

    public Demo(Action action)
    {
        this.action = action;
    }

    public void FirstMethod()
    {
        Console.WriteLine("In first method");
        action();
    }

    public void SecondMethod()
    {
        Console.WriteLine("In second method");
        action();
    }
}

class Test
{
    static void Main()
    {
        Demo demo = new Demo(() => Console.WriteLine("Action called"));

        demo.FirstMethod();
        demo.SecondMethod();
    }
}

答案 1 :(得分:0)

您可以使用backgroundWorker中的InvokeMethod函数来允许worker执行任何委托,例如下面的示例(也等待调用完成,您可能不需要):

BackgroundWorker Function(C ++。net)

BackgroundWorkerFunction()
{
::IAsyncResult ^ThreadResult;

SetTileCount_Delegate ^SetCountDel = gcnew SetTileCount_Delegate(this, &PartDetail::SetTileCount_Function);

//RecordingContainer is the class I am invoking into
ThreadResult = this->RecordingContainer->BeginInvoke(
   SetCountDel, ThisTest->RecordingsCache->Count);

WaitForInvokeTimeOutOrCompletion(ThreadResult);
}




System::Void WaitForInvokeTimeOutOrCompletion(IAsyncResult ^ThreadResult)
{
   if(ThreadResult == nullptr) return;

   long SleepTotal = 0;
   long SleepInterval = 100;

    while ((SleepTotal <= 2000) && !ThreadResult->IsCompleted) 
    {
       ThreadResult->AsyncWaitHandle->WaitOne(SleepInterval, false);
       SleepTotal += SleepInterval;
    }
}
相关问题