Async method which is called from constructor [duplicate] - c#

This question already has answers here:
Can constructors be async?
(15 answers)
Closed 1 year ago.
I have a question regardin the async method which I call in constructor and how to solve or is there a good work around, here is an example
public Constructor()
{
Value = PopulateValueFromDB(); //async method
CalculateInDB(); // async method
}
public async Task<string> PopulateValueFromDB()
{
... do some async calls
return await ...
}
public async Task CalculateInDB()
{
...
return await ...
}
Basically in constructor i have an error, because i cannot use await there, and i cannot make it async.
For CalculateInDB i can make return it void, then i solve the issue with it, although i read somewhere that returning void is not very good solution.
Regarding the PopulateVlaue method ...i have to return something ...
So is there a work around ir i shouldn't use those methods then and make them sync instead of async?

I have a blog post on async constructors that covers a variety of approaches. If possible, I recommend you use the factory pattern, as such:
private Constructor()
{
}
private async Task InitializeAsync()
{
Value = await PopulateValueFromDBAsync();
await CalculateInDBAsync();
}
public static async Task<Constructor> Create()
{
var ret = new Constructor();
await ret.InitializeAsync();
return ret;
}

This is a time to use old tech!
ThreadPool.QueueUserWorkItem.
Cheers -

Related

Using async in a method in a chain [duplicate]

This question already has answers here:
Why use async and return await, when you can return Task<T> directly?
(9 answers)
Closed 2 years ago.
static async Task Main(string[] args)
{
var txt = await GetTask();
}
static Task<string> GetTask()
{
return GetText();
}
static async Task<string> GetText()
{
await Task.Delay(2000);
return "result";
}
Is asynchrony breaking in my case?
Do I need to make the GetTask async method?
If it's a simple forward, no you don't, if there is a chance something in the code block could go wrong, you would have to handle exceptions with Task.FromException to push the exception onto the task (in the way the async and await pattern would), in which case it's probably easier to just use the async keyword and await the awaitables for a small performance hit of the IAsyncStateMachine.

Is it possible to await task completion on different threads? [duplicate]

This question already has answers here:
Async lock not allowed
(2 answers)
Closed 5 years ago.
What I mean is, say we have an async method Task<string> CalculateSha256(string s). Is it possible, that calls from thread #1 and thread #2 are executed consecutively as oposed to being executed concurrently, without threads #1 and #2 knowing anything about each other? For example, I have a controller,
public async Task<string> Get(string value)
{
return await CalculateSha256(value);
}
and I want two different requests to access the chunk of code that's responsible for calculation (CalculateSha256) consecutively.
You need to synchronize the access to CalculateSha256 method that only one thread will execute it at a time.
Since lock statement does not play nicely with async you can use SemaphoreSlim class.
Just add it as a static field to your controller:
private static readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);
And use WaitAsync method in your action (and do not forget to release it when you finish, using finally block):
public async Task<string> Get(string value)
{
await _semaphoreSlim.WaitAsync();
try
{
return await CalculateSha256(value);
}
finally
{
_semaphoreSlim.Release();
}
}
If you find this approach useful and you do not like to reapeat the try finally block you can create a base controller class with a protected generic helper:
protected async Task<T> GetConsecutively(Func<Task<T>> taskFactory)
{
await _semaphoreSlim.WaitAsync();
try
{
return await taskFactory();
}
finally
{
_semaphoreSlim.Release();
}
}
And modify Get method to pass a lambda expression to it:
public async Task<string> Get(string value)
{
return await GetConsecutively(() => CalculateSha256(value));
}
Or alternatively use Stephen Cleary's AsyncLock instead of SemaphoreSlim which supports a high level API closer to the lock statement:
private static readonly AsyncLock _asyncLock = new AsyncLock();
public async Task<string> Get(string value)
{
//Notice the use of using block
//instead of try and finally
using(await _asyncLock.LockAsync())
{
return await CalculateSha256(value);
}
}

Non-Async Method In Async Call Stack [duplicate]

This question already has answers here:
Why use async and return await, when you can return Task<T> directly?
(9 answers)
Closed 5 years ago.
Sorry for a terrible title, I just wanted to confirm that I am making the correct assumptions.
Say I have 3 methods that are simplified to:
public async Task Method1()
{
var obj = await Method2();
//do work on obj
}
public Task<object> Method2()
{
//do some work
return Method3();
}
public async Task<object> Method3()
{
//do async work
return obj;
}
Method2 above does no async work internally, but is in my async stack. It could be rewritten as:
public async Task<object> Method2()
{
//do some work
return await Method3();
}
Am I correct that, as Method2 doesn't actually do async work, that it is better to leave it as a non-async method? My thought is that I'm saving the overhead of creating an extra state machine to hold the thread's resources when it is not needed.
Correct. You can return the Task directly from a method without adding the async/await keywords if the method does not need to await any result (ie. consume the result of a task or wait for a task to complete to be able to do some execution). That returned Task can then be awaited by a caller further down the call stack. This can save a little overhead and make for slightly less code (although that amount of code is actually trivial).
You often see this with pass through or convenience methods.

How do you handle a 3rd party interface returning Task if you don't have any async code? [duplicate]

This question already has answers here:
How to implement interface method that returns Task<T>?
(4 answers)
Closed 6 years ago.
I am working with a third-party dll which exposes methods which return Task and Task<T>. I don't have any control over this assembly or the interface, and I assume the author assumed everything would need to be async since the naming of the methods are *Async() as shown below.
Given that, how do I properly implement the interface if I don't actually have any asynchronous code running?
public interface IFoo
{
Task DoWorkAsync();
Task<int> GetValueAsync();
}
My attempt was the following:
public class FooBar : IFoo
{
public async Task DoWorkAsync()
{
// Do Some Work
await Task.Yield();
}
public async Task<int> GetValueAsync()
{
// Do Some Work
var result = ...;
return Task.FromResult(result);
}
}
Additionally:
Was the author correct in exposing only methods that returned Task/Task<T>?
Was the author correct in suffixing method names with *Async()? Code analysis doesn't complain if I write an async method without appending Async to the name.
If you don't have async work to do don't include the async keyword. Your GetValueAsnyc function was almost correct, you just needed to drop the async. For your DoWorkAsync you should just not mark the method async and return a completed task.
public class FooBar : IFoo
{
public Task DoWorkAsync()
{
// Do Some Work
//If you can use .NET 4.6
return Task.CompletedTask;
//For older versions, the thing you pass in does not matter, I like to use bool.
return Task.FromResult(false);
}
public Task<int> GetValueAsync()
{
// Do Some Work
var result = ...;
return Task.FromResult(result);
}
}
However, if your code is slow and you end up blocking the UI for a long period of time I would consider looking in to if you can re-write your code as actually being async or perhaps wrapping the code in to a background thread, but I would only do a background thread if it was a last resort.

Non async method returning Task<> [duplicate]

This question already has answers here:
Why use async and return await, when you can return Task<T> directly?
(9 answers)
Closed 7 years ago.
I would like to know if there is a difference between these two async patterns. Obviously they will work. I would like to know if there is a hidden trap or performance overhead. What will happen with aggregateexception call stack in both cases?
//------Pattern1-------- PassThruMethod is awaiting
public async void EventHandler()
{
await PassThruMethod();
}
public async Task<int> PassThruMethod()
{
return await MyAsyncMethod();
}
public Task<int> MyAsyncMethod()
{
return Task.Run(() => 1);
}
//---Pattern2----- PassThruMethod is not awaiting
public async void EventHandler()
{
await PassThruMethod();
}
public Task<int> PassThruMethod()
{
return MyAsyncMethod();
}
public Task<int> MyAsyncMethod()
{
return Task.Run(() => 1);
}
There's no need to use async if you don't use await - since your PassThruMethod doesn't need await, don't use it. You can change it at any time if you eventually find out it's not good enough.
Using await does have some overhead (not exactly huge, but there is some), so for a case like this, there's no reason to use it. Returning Task is just fine.

Categories