In my program I add objects to an ObservableCollection
from a background worker thread by utilizing the AddOnUI
extension method used in this answer.
The extension method that I am using:
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());
This solution works perfectly for collection objects that get added from a background worker thread. However, when manually adding a collection object just on the UI thread with no background thread involved, the collection does not populate in data, or in the View. Is there a way to query what thread is active when calling an add method from an ObservableCollection
?
Maybe do something like this?:
if(calling from background thread)
collection.AddOnUI(new B());
else //Manually adding from UI Thread
collection.Add(new B());
Solution:
My solution ended up being a lot similar to my pseudo code, which I really liked.
if(System.Threading.Thread.CurrentThread.IsBackground)
collection.AddOnUI(new B());
else //Manually adding from UI Thread
collection.Add(new B());
Alternate Solution:
AddOnUI()
(Change BeginInvoke
to 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());