【问题标题】:Control.Invoke does not exist in the current context当前上下文中不存在 Control.Invoke
【发布时间】:2011-09-22 15:45:21
【问题描述】:

错误:当前上下文中不存在名称“Invoke”

我正在处理的类已经有一个基类,所以我不能让它实现像 Windows.Forms.Control 这样的东西。

我看了文章here,但我不想实现另一个接口,也不知道我会在方法中放什么。

这是一个相当低级的 C# 适配器程序,因此它无法访问大多数 UI 内容会访问的库

编辑我正在尝试做这样的事情

// On thread X   
Invoke((m_delegate)delegate(){
// Do something on main thread
});

【问题讨论】:

  • 你在问什么?如何使用自定义 Invoke 方法实现线程仿射类?请把问题说清楚。
  • 那段代码一点用也没有。你的基类是什么?
  • @DavidHeffernan 我继承和实现的类都是自定义的,这是程序链中的一个相当低的层次。我正在尝试从主线程上的辅助线程运行一段代码,请参阅代码示例。
  • 一个明显的解决方案是为这些类提供对可以调用 Invoke 的对象的引用。你能做到吗?
  • 您希望委托在哪个线程上执行?

标签: c# multithreading


【解决方案1】:

从您对代码的介绍中很难看出,但也许您可以使用System.Threading.SynchronizationContext 来做您想做的事情。

您只需在您的 UI 线程中捕获上下文(例如通过在那里构造您的对象)并使用 SynchronizationContext.Post 模拟 Control.Invoke

class MyObj
{
   SynchronizationContext _context;

   // please Note: construct the Objects in your main/ui thread to caputure the
   // right context
   public MyObj()
   {
     CaptureCurrentContext();
   }

   // or call this from your main/UI thread
   public void CaptureCurrentContext()
   {
      _context = SynchronizationContext.Current;
   }

   public void MyInvoke(Action a)
   {
       _context.Post((SendOrPostCallback)(_ => a()), null);
   }
}

顺便说一句:对于几乎相同的问题,这是一个非常好的AnswerUsing SynchronizationContext for sending ...

【讨论】:

  • 请注意,除非从主线程调用构造函数,否则这将不起作用。
【解决方案2】:

我最终将Action 委托与匿名方法一起使用,该方法在对象中传递给正确的线程,然后执行。 效果很好,我觉得这段代码很性感。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2019-08-05
    • 2020-07-31
    • 2021-01-16
    • 1970-01-01
    • 2018-06-07
    • 2012-10-23
    • 2021-03-25
    相关资源
    最近更新 更多