简体   繁体   中英

c# background worker in mvvm

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM