C#如何在非静态成员函数上调用Action?

时间:2015-02-02 02:28:30

标签: c# .net multithreading

我有以下代码可行。我传入的动作只是指向同一类静态成员的指针。 (其目的是管理线程以安全地访问正确模式线程上的某些COM对象。)

但现在我想将DoCompute更改为非静态,并且我想使用与DoCompute相同的对象调用func(也更改为非静态)。

如何获取静态输出,以便传入数据?

 public static void DoCompute(Action func)
    {
      Type type = typeof(Computations);
      AppDomain interopDomain = null;
      if (thread != null)
        thread.Join();
      try
      {
          // Define thread.
          thread = new System.Threading.Thread(() =>
          {
              // Thread specific try\catch.
              try
              {
                  // Create a custom AppDomain to do COM Interop.
                string comp = "Computations";
                  interopDomain = AppDomain.CreateDomain(comp);

    //// THIS LINE:  What if func is a non-static member?
                  func.Invoke();

                  Console.WriteLine();
                  Console.WriteLine("End ");
              }
              catch (System.Exception ex)
              {
                  Console.WriteLine(ex.Message);
              }
          });

          // Important! Set thread apartment state to STA.
          thread.SetApartmentState(System.Threading.ApartmentState.STA);

          // Start the thread.
          thread.Start();

          // Wait for the thead to finish.
          thread.Join();
      }
      catch (System.Exception ex)
      {
          Console.WriteLine(ex.Message);
      }
      finally
      {
          if (interopDomain != null)
          {
              // Unload the Interop AppDomain. This will automatically free up any COM references.
              AppDomain.Unload(interopDomain);
          }
      }
  }

1 个答案:

答案 0 :(得分:2)

您只需从两者中删除static个关键字。在引擎盖下,当您将实例方法传递到Action参数时,实例将作为不可见的第一个参数传递。如果将静态方法传递给Action参数,则不会发生这种情况。你唯一不能做的是从静态方法将非静态方法传递给参数。

使用某些代码时可能会更清楚:

public class TestClass
{
    private string _text;

    private void DoCompute(Action func)
    {
        func.Invoke();
    }

    private static void DoComputeStatic(Action func)
    {
        func.Invoke();
    }

    private static void StaticFunc()
    {
        Console.WriteLine("Static func");
    }

    private void NonstaticFunc()
    {
        Console.WriteLine(_text);
    }

    public void Run()
    {
        _text = "Nonstatic func";
        DoCompute(NonstaticFunc);
        DoComputeStatic(StaticFunc); //Can use static method - instance is ignored
    }

    public static void RunStatic()
    {
        DoComputeStatic(StaticFunc);
        //DoCompute(NonstaticFunc);  // Cannot use instance method - no instance
    }

    public void RunWithThread()
    {
        Thread thread = new Thread(() =>
        {
            _text = "Nonstatic func";
            DoCompute(NonstaticFunc);
        });
        thread.Start();
        thread.Join();
    }
}
相关问题