最好的方式来调用任何交叉线程code? [英] Best Way to Invoke Any Cross-Threaded Code?

查看:181
本文介绍了最好的方式来调用任何交叉线程code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经问过,但我正在寻找一种方式来:

I know that this question has been asked before, but I'm looking for a way to:

  1. 简化创建安全跨线程code。
  2. 在重用此code。在任何情况下(没有Windows窗体引用)。

下面是我有这么远,但我想删除Windows窗体参考。任何想法?

Here's what I have so far, but I want to remove the Windows Forms references. Any ideas?

public delegate void SafeInvokeDelegate(System.Action action);
public class SafeInvoke
{
    private readonly System.Windows.Forms.Control _threadControl;

    public SafeInvoke()
    {
    	_threadControl = new System.Windows.Forms.Control();
    }

    public void Invoke(System.Action action)
    {
    	if (_threadControl.InvokeRequired)
    		_threadControl.Invoke(new SafeInvokeDelegate(Invoke), new object[] {action});
    	else if (action != null) action();
    }
}

上面的类可以这样使用:

The above class might be used this way:

SafeInvoke _safeInvoker = new SafeInvoke();
void SafeClearItems()
{
    _safeInvoker.Invoke(delegate
        {
            listView1.Items.Clear();
        });
}

我将如何删除System.Windows.Forms.Control的在SafeInvoke类,但保留了相同的功能?

How would I remove the System.Windows.Forms.Control in the SafeInvoke class but keep the same functionality?

推荐答案

您也可以使用扩展方法和lambda表达式,让您的code干净多了。

You also could use an extension method and lambdas to make your code much cleaner.

using System.ComponentModel;
public static class ISynchronizeInvokeExtensions
{
  public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
  {
    if (@this.InvokeRequired)
    {
      @this.Invoke(action, new object[] { @this });
    }
    else
    {
      action(@this);
    }
  }
}

所以,现在你可以使用 InvokeEx 上的任何ISynchronizeInvoke,并能够访问实现类的属性和字段。

So now you can use InvokeEx on any ISynchronizeInvoke and be able to access the properties and fields of implementing class.

this.InvokeEx(f => f.listView1.Items.Clear());

这篇关于最好的方式来调用任何交叉线程code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆