Допустим, вы выполняете поиск, который приведет к List<Customer>
объекту. Один из довольно простых и простых подходов заключается в том, чтобы вызывать событие по завершении поиска, используя специальный класс EventArgs, содержащий результат:
public class CustomerSearchEventArgs : EventArgs
{
public List<Customer> Customers { get; private set; }
public CustomerSearchEventArgs(List<Customer> customers)
{
Customers = customers;
}
}
... в классе поиска:
// the parameter is there to conform to the signature of the WaitDelegate
// used when invoking the method using the ThreadPool
public void Search(object state)
{
List<Customer> result = new List<Customer>();
// perform the search, populate the result list
// call a method to raise the event
OnSearchFinished(new CustomerSearchEventArgs(result));
}
protected void OnSearchFinished(CustomerSearchEventArgs e)
{
EventHandler<CustomerSearchEventArgs> searchFinished = this.SearchFinished;
if (searchFinished != null)
{
searchFinished(this, e);
}
}
... и в форме:
private delegate void CustomerListHandler(List<Customer> customers);
private void StartSearch()
{
CustomerSearch search = new CustomerSearch();
search.SearchFinished += new EventHandler<CustomerSearchEventArgs>(Search_SearchFinished);
ThreadPool.QueueUserWorkItem(search.Search);
}
private void Search_SearchFinished(object sender, CustomerSearchEventArgs e)
{
SearchFinished(e.Customers);
}
private void SearchFinished(List<Customer> list)
{
if (this.InvokeRequired)
{
// the method is NOT executing on the UI thread; we
// need to invoke it on the right thread
this.Invoke(new CustomerListHandler(SearchFinished), list);
}
else
{
lstCustomers.Items.Clear();
lstCustomers.DisplayMember = "Name";
lstCustomers.Items.AddRange(list.ToArray());
}
}