最好的方式来调用任何交叉线程code?最好的、线程、方式、code

2023-09-02 11:45:00 作者:钓媳妇

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

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

简化创建安全跨线程code。 在重用此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());
 
精彩推荐
图片推荐