I don't understand why the asynchronous method doesn't work

валера карманов 396 Reputation points
2024-10-09T11:20:12.8666667+00:00
public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder.UseMauiApp<App>();

		builder.ConfigureFonts(fonts => {
			fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
			fonts.AddFont("OpenSans-Light.ttf", "OpenSansLight");
			fonts.AddFont("OpenSans-Medium.ttf", "OpenSansMedium");
			fonts.AddFont("OpenSans-Bold.ttf", "OpenSansBold");
		});

		Debug.WriteLine(DateTime.Now + " | Start LoadedUserData");
		LoadedUserData();
		Debug.WriteLine(DateTime.Now + " | End LoadedUserData");

		return builder.Build();
	}

	static async Task LoadedUserData()
	{
		await Task.Run(() => Debug.WriteLine(DateTime.Now + " | Run LoadedUserData"));
	}
}

Объясните что я делаю не так. У меня в консоль выводится "Start", "End" и "Run"

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,607 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 66,866 Reputation points
    2024-10-09T15:46:36.9566667+00:00

    LoadedUserData() is an asynchronous task. but the caller does delay until it completes, so the next line (a debug print) runs before the LoadedUserData() completes. try:

    	    Debug.WriteLine(DateTime.Now + " | Start LoadedUserData");
    		LoadedUserData().Wait();
    		Debug.WriteLine(DateTime.Now + " | End LoadedUserData");
    
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.