Reputation: 100
I have a WCF server application that should accept a call from the client, update in db and return a response to the client. The response to the client is independent in the result of the db update, an exception in the update has no effect on the response. I am using EF6 async methods. I can use Task.Run and inside call the async method:
public Boolean Init(){
//do something
Task.Run(async () => await UpdateDBAsync().ConfigureAwait(false))
.ContinueWith(res => _logger.Warn("cannot insert session to DB"),
TaskContinuationOptions.OnlyOnFaulted);
//do some more
return true;
}
The above will assure that the response to the client will be immediate and will not be dependent in the DB response time. The second approach is not using the Task.Run:
public Boolean Init(){
//do something
UpdateDBAsync().ContinueWith(res => _logger.Warn("cannot insert session to DB"),
TaskContinuationOptions.OnlyOnFaulted);
//do some more
return true;
}
The first approach will allocate a thread pool thread while the second would run on the current thread. My main goal is that the response to the client will be fast as possible and my question is will the first approach (Using the Task.Run) will be faster or will the creation of the thread pool thread decrease the overall performance of the application making the response slower. Note: in the second approach I am using ContinueWith() and not await because I want to do more things and return a response
EDIT
The UpdateDBAsync method:
public async Task UpdateDBAsync()
{
using (var context = SqlConnectionProvider.GetSqlDbEntityContext())
{
try
{
await _retryPolicy.ExecuteAsync(() => context.SaveChangesAsync());
}
catch (DbUpdateException ex)
{
}
}
}
Upvotes: 0
Views: 172
Reputation: 203812
Both are functionally identical, one just needs to take the extra time to be scheduled by a thread pool thread before it can do its work, so yes, it will obviously be slower. It may not be a huge amount slower, but it'll be slower.
The only real possible exception is if UpdateDBAsync
is not actually asynchronous, and in fact does a bunch of work synchronously despite its name. As long as the name is not a lie, there's no reason to use Task.Run
here.
Upvotes: 2