UWP: Task.Wait() always times out in Awake()

Bryce 21 Reputation points
2021-01-14T01:42:37.997+00:00

Hi,

I am trying to read an IP address I already have stored in a text file before my application starts other processes. I have tried ReadIP().Wait() without a timeout and it was stuck loading for much longer than it should without getting the IP from the text file. I know ReadIP works because I can use that in other functions and it retrieves the IP address. I need to get the IP address before my application starts. Does anyone have any suggestion as to what I am doing wrong? Thank you.

private static string fileName = "IP.txt";

string IP = "10.0.0.1";

Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

async void WriteIP()
{
     StorageFile writeFile = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
     await FileIO.WriteTextAsync(writeFile, IP);
}


async Task ReadIP()
{
    try
    {
        StorageFile readFile = await localFolder.GetFileAsync(fileName);
        IP = await FileIO.ReadTextAsync(readFile);
        System.Diagnostics.Debug.WriteLine(IP);
    }
    catch (FileNotFoundException e)
    {
        // Cannot find file
        System.Diagnostics.Debug.WriteLine("No File Found");
    }
    catch (IOException e)
    {
        // Get information from the exception, then throw
        // the info to the parent method.
        if (e.Source != null)
        {
            System.Diagnostics.Debug.WriteLine("IOException source: {0}", e.Source);
        }
        throw;
    }
}


public virtual void Awake()
{
    // Wait for the IP to be retrieved before connecting
    ReadIP().Wait(10000);
}
Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,008 questions
{count} votes

Accepted answer
  1. Heiko 1,261 Reputation points
    2021-01-14T17:22:15.76+00:00

    Hello,

    The execution hangs at the return of localFolder.GetFileAsync() because the execution of the main thread stops/hangs/waits on the Wait() call.

    You could either use await to wait for ReadIP():

    public virtual **async Task** Awake()
    {
     **await** ReadIP();
    }
    

    or with timeout:

    public virtual **async Task** Awake()
    {
     **await** Task.WhenAny(ReadIP(), Task.Delay(10_000));
    }
    

    or you can call ReadIP() completely in a different thread:

    public virtual void Awake()
    {
     Task.Run(() => ReadIP()).Wait(10_000);
    }
    

    I tried to make some words bold within **.


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.