gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:48:01 25 4
gpt4 key购买 nike

在我的程序中,我通过使用 this answer 中使用的 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());

此解决方案非常适用于从后台工作线程添加的集合对象。但是,当仅在不涉及后台线程的 UI 线程上手动添加集合对象时,集合不会填充数据或 View 。从 ObservableCollection 调用 add 方法时,有没有办法查询哪个线程处于事件状态?

也许做这样的事情?:

if(calling from background thread)
collection.AddOnUI(new B());
else //Manually adding from UI Thread
collection.Add(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):

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());

最佳答案

System.Threading.Thread.CurrentThread告诉你你在哪个线程,它可以与 Dispatcher.Thread 进行比较属性(property)。

关于c# - 如何查询正在运行的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26936513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com