Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何查询正在运行的线程_C#_Wpf_Multithreading_Observablecollection - Fatal编程技术网

C# 如何查询正在运行的线程

C# 如何查询正在运行的线程,c#,wpf,multithreading,observablecollection,C#,Wpf,Multithreading,Observablecollection,在我的程序中,我通过使用中使用的AddOnUI扩展方法,从后台工作线程向ObservableCollection添加对象 我正在使用的扩展方法: public static void AddOnUI<T>(this ICollection<T> collection, T item) { Action<T> addMethod = collection.Add; Application.Current.Dispatcher.BeginInvok

在我的程序中,我通过使用中使用的
AddOnUI
扩展方法,从后台工作线程向
ObservableCollection
添加对象

我正在使用的扩展方法:

public static void AddOnUI<T>(this ICollection<T> collection, T item)
{
    Action<T> addMethod = collection.Add;
    Application.Current.Dispatcher.BeginInvoke( addMethod, item );
}

...

collection.AddOnUI(new B());
解决方案:

我的解决方案与我的伪代码非常相似,我非常喜欢它

if(System.Threading.Thread.CurrentThread.IsBackground)
    collection.AddOnUI(new B());
else //Manually adding from UI Thread
    collection.Add(new B());
替代解决方案:

AddOnUI()
(将
BeginInvoke
更改为
Invoke
):

publicstaticvoidaddonUI(此ICollection集合,T项)
{
Action addMethod=collection.Add;
Application.Current.Dispatcher.Invoke(addMethod,item);
}
collection.AddOnUI(新B());

告诉您正在使用哪个线程,它可以与属性进行比较。

检查线程是一个很麻烦的解决方案。您根本不需要它,因为框架内部确保在正确的线程上分派操作

问题很可能是您正在异步添加对象
(BeginInvoke)
。同步添加对象
(调用)
,您将看到该项立即添加到集合中

替换

Application.Current.Dispatcher.BeginInvoke(addMethod, item);


你能详细说明一下它不起作用吗?@RohitVats,当然。我用粗体添加了我的更改。无论如何,它在小样本中对我有效。集合为我更新。两种情况下都只使用
.AddOnUI()
?还是我发布的解决方案?只需
.AddOnUI()
。检查线程绝对是一个黑客解决方案。您是否尝试过在
AddOnUI()
方法中使用
Invoke
来代替
BeginInvoke
?从技术上讲,@Aravol的解决方案也很有效,但我选择实现Rohit-Vat的解决方案,因为它的简单性和更好的抽象性。
public static void AddOnUI<T>(this ICollection<T> collection, T item)
{
    Action<T> addMethod = collection.Add;
    Application.Current.Dispatcher.Invoke(addMethod, item);
}

collection.AddOnUI(new B());
Application.Current.Dispatcher.BeginInvoke(addMethod, item);
Application.Current.Dispatcher.Invoke(addMethod, item);