UI still freezes using backgroundWorker

给你一囗甜甜゛ 提交于 2019-12-01 23:40:24

A few things here. 1) Your worker and its delegates should be created when your object containing it is instantiated.

public class ViewModel 
{
    BackgroundWorker _primeWorker;

    public ViewModel()
    {
        _primeWorker = new BackgroundWorker;

        _primeWorker.DoWork += ...
    }

    public void AddSomeNumbers()
    {
         if(_primerWorker.IsBusy == false)
              _primeWorker.RunWorkerAsync();
    }
}

2) Your collection should be instantiated when the object containing it is instantiated to avoid a null exception being thrown should the object using this class calls the get.

3) Adding that many items would cause slowness due to each time you add a number an event is fired that the UI thread has to handle.

This link has more info to help you out. http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx

yield won't help you here. RunWorkerCompleted executes on the UI thread. Apparently instantiating the ObservableCollection<int> is taking a long time. The simplest solution may be to move the instantiation to the background thread (DoWork) as well. It could also be a PropertyChanged event handler that is taking a long time, in which case it should also run on a background thread.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!