Dave New
Dave New

Reputation: 40002

Binding data to a grid control on a separate thread

I am using Tasks to fetch data on a separate thread so that the user can continue using the application. The problem I found is that the actual binding of my data to my grid also takes a few seconds. How can I bind my data on the same thread as my FetchData() call?

Task<List<SomeData>> getData = new Task<List<SomeData>>(() =>
{
    List<SomeData> myData = FetchData(); // Expensive!
    return myData;
});

getData.Start();

Task processData = getData.ContinueWith(data =>
{
    grid.DataSource = data; // Takes a few second so now the UI thread is disrupted
}, TaskScheduler.FromCurrentSynchronizationContext()); // UI thread :(

Upvotes: 3

Views: 693

Answers (1)

Jaska
Jaska

Reputation: 1430

How about using a BackgroundWorker? Just pull the backgroundworker from toolbox into the form, then start the process with BackgroundWorker's RunWorkerAsync call.

In the DoWork event, do the data fetching.

In the RunWorkerCompleted event, bind the results to grid.

Upvotes: 1

Related Questions