iisystems
iisystems

Reputation: 1147

Task.Factory.StartNew with multiple parameters

I'm trying to refactor some code to achieve more throughput through parallelism. I did all the base refactoring to where I had my minimalist single call that would be thread-safe. My method takes multiple parameters:

private Domain ImportDomain(ConstructorInfo domainConstructor,
                            string[] domainAttributes, DateTime importDate)
{
    ...
}

I have working code which iterates calls to this method, simply as such:

ImportDomain(myConstructor, myAttributes, myDate);

All works totally fine before I try adding in parallelism.

I thought I would simply be able to do this:

Task<Domain>.Factory.StartNew(() =>
    ImportDomain(myConstructor, myAttributes, myDate)
);

and add a catch block to handle any AggregateException which might be thrown.

However, what I found was that ImportDomain() was never called with this code, although the StartNew() line was executing. I have a feeling this may be due to my relative inexperience with lambda expressions, but I'm also seeing that all examples using StartNew() either use delegates, or pass a single param.

What is the simplest solution to making my multi-parameter call compatible with Task.Factory.StartNew()?

Upvotes: 2

Views: 9370

Answers (1)

gooch
gooch

Reputation: 575

I think what you need is to name the task, and get the Result of the completed import.

Task<Domain> someDomainTask = Task<Domain>.Factory.StartNew(() => 
  { 
    return ImportDomain(myConstructor, myAttributes, myDate);
  } 
);
Domain someDomain = someDomainTask.Result;

Upvotes: 7

Related Questions