简体   繁体   中英

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?

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

string userName = await GetUsername();
//Line2

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM