Stephen K
Stephen K

Reputation: 737

Thread pooling, multiple threads, async, etc. What should I use?

My scenario:

What solution should I employ? Thread pool? Create/destroy threads as needed? I have most of the code written, but need the searching/updating to not be on the UI thread. Where is a good place to start?

Edit: I must use .NET 3.5 and can't use things like async/await :(

Upvotes: 2

Views: 99

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564451

In general, this sounds like the language based async/await keywords are likely the best option, for two reasons:

  • An operation on a web service is run on each of these items

Given that this is a web service call, it's going to be naturally IO bound and asynchronous. Using the TPL or other routines (without care) may reduce the overall throughput. In general, you want these operations to stay asynchronous and will scale the best if you treat them that way from the start.

  • A DataGridView is bound to some BindingList/ObservableCollection of classes and updates upon completion of each operation
  • There might also be a status label informing the user how many items have completed.

Given that you're binding UI controls to the results, the async/await support to map calls back onto the calling synchronization context will simplify adding the results into your collections. This will keep the code very simple in its final state.

Note that you may want to store the Task<T> returned by the async operations, then await the returned values (not just await the message call directly). This will allow you to fire off multiple requests to the services at the same time. For example, your code will likely look something like (*without exception handling, etc):

// Start each operation, and store in a list

var asyncOperations = ids.Select(id => FetchDataFromWebServiceAsync(id)).ToList();

while (asyncOperations.Any())
{
    // When one operation completes, remove it from the list of ops running
    var completed = await Task.WhenAny(asyncOperations);
    asyncOperations.Remove(completed);

    // Grab the result and use
    YourResultType finished = completed.Result;
    // Add to UI, update progress, etc...
}

Upvotes: 3

Related Questions