-
Notifications
You must be signed in to change notification settings - Fork 773
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AsyncGuidance - Constructors and DI #63
Comments
One option is to delay initialization until method invocation occurs. Basically: public async Task FooAsync()
{
await EnsureInitializedAsync();
//do actual operation
} The RedisCache class is a good example of this pattern. It does not connect to Redis until the first interaction with the server: |
Thanks for your reply @epignosisx, What if I need to call Async method and the value retured is used by next statement in within Contructor? UI is depended on this so has to happen within Constructor. May be not the best example.. public interface IFoo { }
public class Foo : IFoo
{
// Instance will be created from Container (IServiceProvider)
// and so cannot use static factory pattern
public Foo(IService service)
{
// Only have Async method on the API
// Is this the best right way or there is a better way of achieving the same?
var a = service.BarAsync().GetAwaiter().GetResult();
DoSomethingWith(a); // Now part of UI may be depended on value a
DoSomethingElseWith(a); // And another part of UI may be depended on value a
}
} |
The option I brought up was about moving the constructor async logic to a class method upon invocation. I’m struggling to understand why this logic must be in the constructor. When you say UI, which technology are you referring to? Razor View? WPF/UWP Xaml? |
@epignosisx, may be it is just a bad example or may be I need to rephrase it. To rephrase my query, if you forget about this Async call in Constructor for now. What shall I use or what is the safest to use on WPF/UWP/Xamarin.Forms and ASP.NET Core? public interface IFoo { }
public class Foo : IFoo
{
public Foo(IService service)
{
var a = service.BarAsync().GetAwaiter().GetResult();
}
public void Bar()
{
var a = service.BarAsync().GetAwaiter().GetResult();
}
} public void Bar()
{
// Task may return result or not depending on the requirement so this can be ignored.
// Is this the best (right?) way or there is a better way of achieving the same?
service.BarAsync().GetAwaiter().GetResult();
// The same can be achieved in many different ways.
service.BarAsync().RunSynchronously();
service.BarAsync().Wait();
service.BarAsync().Result;
} |
@mihirdilip Generally speaking, you should avoid The section Avoid using If you really have to do some As an example, that could be a small Utility class for your needs, still not recommended to use sync over async: public static class AsyncUtility
{
/// <summary>
/// Executes an async operation synchronously without risking a deadlock.
/// </summary>
/// <typeparam name="T">The result type of the operation.</typeparam>
/// <param name="asyncOperation">The async operation.</param>
/// <returns>The operation result.</returns>
public static T ExecuteSynchronously<T>(Func<Task<T>> asyncOperation)
{
return Task.Run(asyncOperation).Result;
}
/// <summary>
/// Executes an async operation synchronously without risking a deadlock.
/// </summary>
/// <param name="asyncOperation">The async operation.</param>
public static void ExecuteSynchronously(Func<Task> asyncOperation)
{
Task.Run(asyncOperation).Wait();
}
} |
@epignosisx and @kapsiR |
If there's no way to avoid it then you're in the bad situation described in the document. There's no workaround for needing to block using Task.Wait or Task.Result, nor is there a good way to do it. |
@davidfowl, Constructors section explains getting around by using static factory pattern.
But, what happens when I cannot call this static method to create an instance because the instance is created by container when
IService
is dependency injected via constructor into other class?Basically, what is the best practice for calling Async method in within constructor for these 2 different scenarios?
Task.Run(BackgroundOperationAsync);
?The text was updated successfully, but these errors were encountered: