Reputation: 971
I am using treeview in my wpf application. Child elements must load in background thread.
What should I use for this task? Background worker? How should I rewrite it? My viewmodel is:
public class SpaceObjectViewModel : TreeViewItemViewModel
{
private SpaceObject mSpaceObject;
private BackgroundWorker mBackgroundWorker;
public SpaceObjectViewModel(SpaceObject spaceObject, SpaceObjectViewModel parentViewModel)
: base(parentViewModel, true)
{
mSpaceObject = spaceObject;
}
public string Name
{
get { return mSpaceObject.Name; }
}
protected override void LoadChildren()
{
foreach (SpaceObject space in DataManager.Instance.Read(mSpaceObject.ObjectId))
base.Childrens.Add(new SpaceObjectViewModel(space, this));
}
}
Upvotes: 1
Views: 1481
Reputation: 17600
In .net 4.5 you can use async/await like this:
protected async override void LoadChildren()
{
foreach (SpaceObject space in await Task.Run(() => DataManager.Instance.Read(mSpaceObject.ObjectId)))
base.Childrens.Add(new SpaceObjectViewModel(space, this));
}
Because of the await
you need async
in your signature.
Task.Run(() => ...)
Queues the specified work to run on the ThreadPool and returns a task or Task(TResult) handle for that work.
Upvotes: 2