Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 什么';创建异步服务的正确模式是什么?_.net_Multithreading_Silverlight_Asynchronous_Windows Phone 7 - Fatal编程技术网

.net 什么';创建异步服务的正确模式是什么?

.net 什么';创建异步服务的正确模式是什么?,.net,multithreading,silverlight,asynchronous,windows-phone-7,.net,Multithreading,Silverlight,Asynchronous,Windows Phone 7,以下是我想做的: public class EmployeeService { public void GetEmployeesAsyc(Action<IEnumerable<Employees>> callback) { ThreadPool.QueueUserWorkItem(x => { var employees = //...fetch employees ...// ca

以下是我想做的:

public class EmployeeService
{
    public void GetEmployeesAsyc(Action<IEnumerable<Employees>> callback)
    {
        ThreadPool.QueueUserWorkItem(x => {
             var employees = //...fetch employees ...//
             callback(employees);
        });
    }
}

public class ViewModel
{
    private EmployeeService _employeeService;
    private bool _isLoaded;

    public ViewModel() 
    { 
         _employeeService = new EmployeeService();   
         EmployeeList = new ObservableCollection<Employee>();
    }

    public ObservableCollection<Employee> EmployeeList { get; set; }

    public void LoadData()
    {
         if(_isLoaded) return;

         _employeeService.GetEmployeesAsync(employees => 
         {
             EmployeeList.Clear();
             employees.ForEach(employee => EmployeeList.Add(employee));          
         });

         _isLoaded = true;
    }
}

public partial class View : PhoneApplicationPage
{
     private ViewModel _vm;

     public View()
     {
         InitializeComponent();
         _vm = new ViewModel();
         this.Loaded += (sender, e) => _vm.LoadData();
     }
}
我可以这样包装它来修复它:

         _employeeService.GetEmployeesAsync(employees => 
         {
             Dispatcher.BeginInvoke(() =>
             {
                 EmployeeList.Clear();
                 employees.ForEach(employee => EmployeeList.Add(employee));          
             });
         });

但我不确定这样做是否正确。有什么建议吗?

使用dispatcher将您的UI更改从后台线程转移到UI线程上没有错。这是它的主要目的之一

某些框架元素为您内置了此功能(如webclient vs httpwebrequest),以避免编写调度程序代码的麻烦,但如果您正在执行大量工作,则使用此功能可能会导致UI性能下降,因为您的代码比在UI线程上执行所需的代码多。在资源受限的设备(如WP7)上运行的应用程序对此特别敏感

         _employeeService.GetEmployeesAsync(employees => 
         {
             Dispatcher.BeginInvoke(() =>
             {
                 EmployeeList.Clear();
                 employees.ForEach(employee => EmployeeList.Add(employee));          
             });
         });