user2256870
user2256870

Reputation: 955

Xamarin Android: Read local storage (PCLStorage) file with synchronize

I can read a local storage file with following code:

public static async Task<string> GetUserName()
        {
            string value = String.Empty;
            IFolder rootFolder = FileSystem.Current.LocalStorage;

            // Read file
            ExistenceCheckResult exist = await rootFolder.CheckExistsAsync(FILE_NAME);
            if (exist == ExistenceCheckResult.FileExists)
            {
                IFile file = await rootFolder.GetFileAsync("myusername.txt");
                value = await file.ReadAllTextAsync();                
            }

            return value;
        }

I call this function like below:

Line1: Task<String> userName = GetUserName();
Line2: // Doing some task.

Here before exucuting Line2 i need the userName from Line1. But because of Async operation Line2 start executing without getting userName from Line1.

So how can i execute Line2 after I get userName in Line1?

Upvotes: 1

Views: 172

Answers (1)

MilanG
MilanG

Reputation: 2604

You need to await while calling GetUsername() method like,

string userName = await GetUsername();
//Line2

Thus, it will wait for username before Line2 gets executed.

Upvotes: 2

Related Questions