user3651656
user3651656

Reputation: 185

(C#) Run a command after a successful execution of FileIO.ReadTextAsync

I'm setting the content of a RichEditBox through a file read operation like so:

Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, await FileIO.ReadTextAsync(file));

But I want to run a few more commands only if and when the asynchronous read operation is complete. Juding by the documentation, something similar is possible in WinJS through a .done() command. But I'm using C# and XAML, so I need to find another way.

My guess is that this can be done using AsyncStatus.

I've tried setting up the following code, but I don't know what replace ?????? with:

AsyncStatus status = ??????;
if (status == AsyncStatus.Completed)
{
    // Do something.
}
else
{
    // An error occurred.
}

Is there some way to get this to work? Is there another (better?) method to do this?

Upvotes: 0

Views: 94

Answers (2)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

@Mark is right, the method will return as soon as it kicks off the ReadTextAsync method and once it completes, if there is no error the SetText call will go ahead. Otherwise an exception will be thrown. You can catch that if you need to log an error etc.

public async void SetText(string file)
{
    try
    {           
        var text = await FileIO.ReadTextAsync(file);

        //ReadTextAsync succeeded, set text 
        Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
    }
    catch (Exception ex)
    {
        // error do something
        throw;
    }
}

Upvotes: 0

Mark
Mark

Reputation: 8160

I'm not familiar with Windows Store apps, so maybe I am missing something, but since you are awaiting the FileIO.ReadTextAsync call, your method will block until the SetText call is complete, so you can simply code the other commands after that:

Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, await FileIO.ReadTextAsync(file));
// Do other stuff - ReadTextAsync will have finished by now.

Upvotes: 1

Related Questions