81

我发现.NET 事件模型是这样的,我经常会在一个线程上引发一个事件并在另一个线程上监听它。我想知道将事件从后台线程编组到我的 UI 线程的最干净的方法是什么。

根据社区的建议,我使用了这个:

// earlier in the code
mCoolObject.CoolEvent+= 
           new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        CoolObjectEventHandler cb =
            new CoolObjectEventHandler(
                mCoolObject_CoolEvent);
        Invoke(cb, new object[] { sender, args });
        return;
    }
    // do the dirty work of my method here
}
4

10 回答 10

45

我有一些在线代码。它比其他建议要好得多;一定要检查一下。

示例用法:

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    // You could use "() =>" in place of "delegate"; it's a style choice.
    this.Invoke(delegate
    {
        // Do the dirty work of my method here.
    });
}
于 2008-11-03T11:30:56.523 回答
28

几点观察:

  • 不要在这样的代码中显式创建简单的委托,除非您是 2.0 之前的版本,因此您可以使用:
   BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent), 
               sender, 
               args);
  • 此外,您不需要创建和填充对象数组,因为 args 参数是“params”类型,因此您只需传入列表即可。

  • 我可能会赞成InvokeBeginInvoke因为后者会导致代码被异步调用,这可能是也可能不是你所追求的,但如果不调用EndInvoke. 会发生什么是你的应用程序最终会得到一个TargetInvocationException

于 2008-08-22T13:45:40.993 回答
11

我避开了多余的委托声明。

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        Invoke(new Action<object, CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args);
        return;
    }
    // do the dirty work of my method here
}

对于非事件,您可以使用System.Windows.Forms.MethodInvoker委托或System.Action.

编辑:此外,每个事件都有一个相应EventHandler的委托,因此根本不需要重新声明一个。

于 2008-08-22T13:42:47.477 回答
6

我出于自己的目的制作了以下“通用”跨线程调用类,但我认为值得分享它:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace CrossThreadCalls
{
  public static class clsCrossThreadCalls
  {
    private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);
    public static void SetAnyProperty(Control c, string Property, object Value)
    {
      if (c.GetType().GetProperty(Property) != null)
      {
        //The given property exists
        if (c.InvokeRequired)
        {
          SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);
          c.BeginInvoke(d, c, Property, Value);
        }
        else
        {
          c.GetType().GetProperty(Property).SetValue(c, Value, null);
        }
      }
    }

    private delegate void SetTextPropertyCallBack(Control c, string Value);
    public static void SetTextProperty(Control c, string Value)
    {
      if (c.InvokeRequired)
      {
        SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);
        c.BeginInvoke(d, c, Value);
      }
      else
      {
        c.Text = Value;
      }
    }
  }

您可以简单地从另一个线程使用 SetAnyProperty() :

CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());

在这个例子中,上面的 KvaserCanReader 类运行它自己的线程并调用设置主窗体上 lb_Speed 标签的文本属性。

于 2012-10-05T09:36:06.550 回答
3

我认为最干净的方法肯定是走 AOP 路线。做几个方面,添加必要的属性,你再也不用检查线程亲和性了。

于 2009-04-29T17:33:31.610 回答
3

如果要将结果发送到 UI 线程,请使用同步上下文。我需要更改线程优先级,所以我改变了使用线程池线程(注释掉的代码)并创建了一个我自己的新线程。我仍然能够使用同步上下文来返回数据库取消是否成功。

    #region SyncContextCancel

    private SynchronizationContext _syncContextCancel;

    /// <summary>
    /// Gets the synchronization context used for UI-related operations.
    /// </summary>
    /// <value>The synchronization context.</value>
    protected SynchronizationContext SyncContextCancel
    {
        get { return _syncContextCancel; }
    }

    #endregion //SyncContextCancel

    public void CancelCurrentDbCommand()
    {
        _syncContextCancel = SynchronizationContext.Current;

        //ThreadPool.QueueUserWorkItem(CancelWork, null);

        Thread worker = new Thread(new ThreadStart(CancelWork));
        worker.Priority = ThreadPriority.Highest;
        worker.Start();
    }

    SQLiteConnection _connection;
    private void CancelWork()//object state
    {
        bool success = false;

        try
        {
            if (_connection != null)
            {
                log.Debug("call cancel");
                _connection.Cancel();
                log.Debug("cancel complete");
                _connection.Close();
                log.Debug("close complete");
                success = true;
                log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());
            }
        }
        catch (Exception ex)
        {
            log.Error(ex.Message, ex);
        }

        SyncContextCancel.Send(CancelCompleted, new object[] { success });
    }

    public void CancelCompleted(object state)
    {
        object[] args = (object[])state;
        bool success = (bool)args[0];

        if (success)
        {
            log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());

        }
    }
于 2015-07-07T08:20:11.820 回答
2

我一直想知道总是假设需要调用是多么昂贵......

private void OnCoolEvent(CoolObjectEventArgs e)
{
  BeginInvoke((o,e) => /*do work here*/,this, e);
}
于 2008-08-22T13:44:28.267 回答
2

作为一个有趣的附注,WPF 的绑定自动处理封送处理,因此您可以将 UI 绑定到在后台线程上修改的对象属性,而无需执行任何特殊操作。事实证明,这对我来说是一个很好的节省时间。

在 XAML 中:

<TextBox Text="{Binding Path=Name}"/>
于 2008-08-22T14:20:36.213 回答
0

您可以尝试开发某种通用组件,该组件接受SynchronizationContext作为输入并使用它来调用事件。

于 2008-08-22T13:53:17.420 回答
-3

我正在使用类似的东西

Invoke((Action)(() =>
        {
            //your code
        }));
于 2021-03-14T20:35:31.363 回答