Linq to Sql导致组合框异步

时间:2011-09-20 23:56:48

标签: c# winforms linq-to-sql

我正在开发一个winform应用程序,并在数据库中发出请求并异步填充我的组合框,但是我遇到了访问控制问题,因为它们来自另一个线程,这是代码。

   this.backWorker.DoWork + = delegate
             {
                 comboBoxUsers.DataSource = repositoryUser.SelectAll();
                 comboBoxUsers.ValueMember = "UserId";
                 comboBoxUsers.DisplayMember = "Name";
             };

             backWorker.RunWorkerAsync ();

我正在研究envoke,但是我无法实现这个, 我需要做的是将DoWork事件留在可见的进度条中并选择执行此操作。

2 个答案:

答案 0 :(得分:3)

仅查询BackgroundWorker上的存储库,并通过ProgressChangedEvenHandler将结果返回给UI

   //Set the ComboBox Properties on the Form, not in the worker.
   comboBoxUsers.ValueMember = "UserId";
   comboBoxUsers.DisplayMember = "Name";

   BackgroundWorker = new BackgroundWorker();
   worker.DoWork += Worker_DoWork;
   worker.WorkerReportsProgress = true;
   worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged);

   private void Worker_DoWork(object sender, DoWorkEventArgs e)
   {
        BackgrounderWorker worker = (BackgroundWorker)sender;

        //Query the database
        //Instantiate a custom-class to contain the results
        IList<Users> users = userRepository.SelectAll();
        QueryResults results = new QueryResults(users);
        worker.ReportProgress(0, results);
   }

   //Back In the UI Layer
   private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
   {
       var result = (QueryResult)e.UserState;
       comboBoxUsers.DataSource = result.Users;
   }

答案 1 :(得分:0)

你的代表应该这样写:

this.backWorker.DoWork += delegate(object s, DoWorkEventArgs args)
{
  //...
}

有关如何从另一个线程访问UI线程的UI控件的详细信息,请参阅此处:

Access windows control from Backgroundworker DoWork

该链接有一个明确的答案,这里是一个片段:

this.Invoke(new MethodInvoker(delegate {

  // This code executes on the GUI thread.

}));