So, my app worked with sync methods, but it stops as I use async methods.
This is a code in my class when object creates.
_isAdult = (DateСalculation.CalculateAgeAsync(DateOfBirth).Result >= 18);
_sunSign = DateСalculation.CalculateSunSignAsync(DateOfBirth).Result;
_chineseSign = DateСalculation.CalculateSunSignAsync(DateOfBirth).Result;
_isBirthday = DateСalculation.IsBirthdayAsync(DateOfBirth).Result;
And this is async methods.
public static class DateCalculation
{
public static string CalculateSunSign(DateTime date){...}
public static async Task<string> CalculateSunSignAsync(DateTime date)
{
return await Task.Run(() => CalculateSunSign(date));
}
public static string CalculateChineseSign(DateTime date) {...}
public static async Task<string> CalculateChineseSignAsync(DateTime date)
{
return await Task.Run(() => CalculateChineseSign(date));
}
public static int CalculateAge(DateTime date) {...}
public static async Task<int> CalculateAgeAsync(DateTime date)
{
return await Task.Run(() => CalculateAge(date));
}
public static bool IsBirthday(DateTime date) {...}
public static async Task<bool> IsBirthdayAsync(DateTime date)
{
return await Task.Run(() => IsBirthday(date));
}
}
CodePudding user response:
Whenever using async, await, you should not use .Result
(unless you have to) because it blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.
So change the code as per below:
_isAdult = (await (DateСalculation.CalculateAgeAsync(DateOfBirth)) >= 18);
_sunSign = await DateСalculation.CalculateSunSignAsync(DateOfBirth);
_chineseSign = await DateСalculation.CalculateSunSignAsync(DateOfBirth);
_isBirthday = await DateСalculation.IsBirthdayAsync(DateOfBirth);
Checking Asynchronous programming with async and await documentation can help you.