【问题标题】:Fire event from Async component in UI threadUI线程中异步组件的触发事件
【发布时间】:2011-01-02 14:02:09
【问题描述】:

我正在.Net 2.0 中构建一个非可视组件。该组件使用异步套接字(BeginReceive、EndReceive 等)。在运行时创建的工作线程的上下文中调用异步回调。组件用户不必担心多线程(这是主要目标,我想要的)

组件用户可以在任何线程中创建我的非可视组件(UI 线程只是简单应用程序的公共线程。更严重的应用程序可以在任意工作线程中创建组件)。组件触发“SessionConnected”或“DataAvailable”等事件。

问题:由于异步回调和其中引发的事件,事件处理程序在工作线程上下文中执行。我想使用一个中间层来强制 要在创建的线程的上下文中执行的事件处理程序 组件放在首位。

示例代码(从异常处理等中剥离...)

    /// <summary>
    /// Occurs when the connection is ended
    /// </summary>
    /// <param name="ar">The IAsyncResult to read the information from</param>
    private void EndConnect(IAsyncResult ar)
    {
        // pass connection status with event
        this.Socket.EndConnect(ar);

        this.Stream = new NetworkStream(this.Socket);

        // -- FIRE CONNECTED EVENT HERE --

        // Setup Receive Callback
        this.Receive();
    }


    /// <summary>
    /// Occurs when data receive is done; when 0 bytes were received we can assume the connection was closed so we should disconnect
    /// </summary>
    /// <param name="ar">The IAsyncResult that was used by BeginRead</param>
    private void EndReceive(IAsyncResult ar)
    {
        int nBytes;
        nBytes = this.Stream.EndRead(ar);
        if (nBytes > 0)
        {
            // -- FIRE RECEIVED DATA EVENT HERE --

            // Setup next Receive Callback
            if (this.Connected)
                this.Receive();
        }
        else
        {
            this.Disconnect();
        }
    }

由于异步套接字的性质,所有使用我的组件的应用程序都充斥着“If (this.InvokeRequired) { ...”,我想要的只是用户能够无忧无虑地使用我的组件作为排序一个临时的。

那么我将如何在不要求用户检查 InvokeRequired 的情况下引发事件(或者,换句话说,我如何强制在与最初启动事件的线程相同的线程中引发事件)?

我已经阅读了有关 AsyncOperation、BackgroundWorkers、SynchronizingObjects、AsyncCallbacks 和大量其他内容的资料,但这一切都让我头晕目眩。

我确实想出了这个,肯定是笨拙的“解决方案”,但在某些情况下似乎会失败(例如,当我的组件通过静态类从 WinForms 项目中调用时)

    /// <summary>
    /// Raises an event, ensuring BeginInvoke is called for controls that require invoke
    /// </summary>
    /// <param name="eventDelegate"></param>
    /// <param name="args"></param>
    /// <remarks>http://www.eggheadcafe.com/articles/20060727.asp</remarks>
    protected void RaiseEvent(Delegate eventDelegate, object[] args)
    {
        if (eventDelegate != null)
        {
            try
            {
                Control ed = eventDelegate.Target as Control;
                if ((ed != null) && (ed.InvokeRequired))
                    ed.Invoke(eventDelegate, args);
                else
                    eventDelegate.DynamicInvoke(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.GetType());
                Console.WriteLine(ex.Message);
                //Swallow
            }
        }
    }

任何帮助将不胜感激。提前致谢!

编辑: 根据this thread,我最好的选择是使用SyncrhonizationContext.Post,但我不知道如何将其应用于我的情况。

【问题讨论】:

    标签: c# user-interface asynchronous sockets invokerequired


    【解决方案1】:

    好的;所以这就是我在阅读更多内容后得到的结果:

    public class MyComponent {
        private AsyncOperation _asyncOperation;
    
        /// Constructor of my component:
        MyComponent() {
            _asyncOperation = AsyncOperationManager.CreateOperation(null);
        }
    
        /// <summary>
        /// Raises an event, ensuring the correct context
        /// </summary>
        /// <param name="eventDelegate"></param>
        /// <param name="args"></param>
        protected void RaiseEvent(Delegate eventDelegate, object[] args)
        {
            if (eventDelegate != null)
            {
                _asyncOperation.Post(new System.Threading.SendOrPostCallback(
                    delegate(object argobj)
                    {
                        eventDelegate.DynamicInvoke(argobj as object[]);
                    }), args);
            }
        }
    }
    

    此处发布的另一个解决方案是一种正在进行中的工作。此处发布的解决方案似乎(根据 MSDN)是迄今为止最好的。非常非常欢迎提出建议。

    【讨论】:

      【解决方案2】:

      我似乎找到了解决办法:

          private SynchronizationContext _currentcontext
      
          /// Constructor of my component:
          MyComponent() {
              _currentcontext = WindowsFormsSynchronizationContext.Current;
             //...or...?
              _currentcontext = SynchronizationContext.Current;
          }
      
          /// <summary>
          /// Raises an event, ensuring the correct context
          /// </summary>
          /// <param name="eventDelegate"></param>
          /// <param name="args"></param>
          protected void RaiseEvent(Delegate eventDelegate, object[] args)
          {
              if (eventDelegate != null)
              {
                  if (_currentcontext != null)
                      _currentcontext.Post(new System.Threading.SendOrPostCallback(
                          delegate(object a)
                          {
                              eventDelegate.DynamicInvoke(a as object[]);
                          }), args);
                  else
                      eventDelegate.DynamicInvoke(args);
              }
          }
      

      我仍在测试它,但它似乎工作正常。

      【讨论】:

      • 当你的组件不是在 UI 线程上创建时,这种方法会发生什么?
      • 我忘记粘贴我最新的编辑,它检查 _currentcontext 是否为空;现在已修复(并已编辑)。
      • 我刚刚查了一下,如果你在组件的构造函数中捕获了 SynchronizationContext 并且组件是在非 UI 线程中创建的,那么你的 eventDelegate 将在 ThreadPool 上执行。
      • 我现在使用 WindowsFormsSynchronizationContext(我再次编辑了我的“解决方案”)。那会有什么不同吗?恐怕我对这个话题一无所知。我使用控制台应用程序和 WinForms 应用程序检查了这一点,两者似乎都可以正常工作。
      【解决方案3】:

      如果您的组件必须始终由同一个线程使用,您可以执行以下操作:

      public delegate void CallbackInvoker(Delegate method, params object[] args);
      
      public YourComponent(CallbackInvoker invoker)
      {
          m_invoker = invoker;
      }
      
      protected void RaiseEvent(Delegate eventDelegate, object[] args)
      {
          if (eventDelegate != null)
          {
              try
              {
                  if (m_invoker != null)
                      m_invoker(eventDelegate, args);
                  else
                      eventDelegate.DynamicInvoke(args);
              }
              catch (Exception ex)
              {
                  Console.WriteLine(ex.GetType());
                  Console.WriteLine(ex.Message);
                  //Swallow
              }
          }
      }
      

      然后,当您从表单或其他控件实例化您的组件时,您可以这样做:

      YourComponent c = new YourComponent(this.Invoke);
      

      要在非 UI 工作线程上对事件进行排队,它必须具有某种工作排队机制,然后您可以提供一个带有 CallbackInvoker 签名的方法,以便在工作线程上对委托进行排队。

      【讨论】:

      • 这给使用我的组件的用户带来了太多的复杂性。
      • 复杂性在哪里?在组件的构造函数中指定委托?
      • 我希望我的组件是透明异步的(所以最终用户不会注意到)。当最终用户没有(明显的)原因必须通过委托时,我认为这不是“用户友好的”。不过,我似乎找到了解决方案;但我不确定这是否是“最佳”解决方案。
      【解决方案4】:

      也许我不理解这个问题,但在我看来,您可以只传递对处于异步状态的自定义对象的引用。

      我整理了下面的例子来说明;

      首先我们有一个回调对象。这有 2 个属性 - 一个用于调度操作的控件和一个用于调用的操作;

      public class Callback
      {
          public Control Control { get; set; }
          public Action Method { get; set; }
      }
      

      然后我有一个 WinForms 项目,它在另一个线程上调用一些随机代码(使用 BeginInvoke),然后在代码执行完成时显示一个消息框。

          private void Form1_Load(object sender, EventArgs e)
          {
              Action<bool> act = (bool myBool) =>
                  {
                      Thread.Sleep(5000);
                  };
      
              act.BeginInvoke(true, new AsyncCallback((IAsyncResult result) =>
              {
                  Callback c = result.AsyncState as Callback;
                  c.Control.Invoke(c.Method);
      
              }), new Callback()
              {
                  Control = this,
                  Method = () => { ShowMessageBox(); }
              });            
          }
      

      ShowMessageBox 方法必须在 UI 线程上运行,如下所示:

          private void ShowMessageBox()
          {
              MessageBox.Show("Testing");
          }
      

      这是你要找的吗?

      【讨论】:

      • 不是真的;在使用我的组件时,这对人们来说是一种复杂的方式。所有要做的就是引用组件并使用如下代码: //Initialize MyComponent with IP, port etc. 然后: MyComponent.SendString("This is cool"); MyComponent 引发事件;它们是由 GUI 项目还是非 GUI 项目处理无关紧要,我不希望用户负责检查 InvokeRequired。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2022-10-18
      相关资源
      最近更新 更多