Home > Software engineering >  Baffled by Async, Await and Task - need guidance
Baffled by Async, Await and Task - need guidance

Time:10-23

I'm afraid the more I read, the more baffled I get. I think I need a real world example. I'm stuck in some code in a MVVM WPF app. How do I get NetworkPlaces running asyncronously so it doesn't block the UI thread? I've tried loads of different combinations of async, task and await.

A lot of the examples seem to use 'end' methods that have asynchronous methods within it such as .ReadToEndAsync or .GetStringAsync. One advisory (and UI freeze) I kept getting was about NetworkPlaces not having an Async method.

Here's my illustration code at the moment. I'd be grateful if someone could show mw some working code:

public RelayCommand ScanForDevicesCMD { get; private set; }


public MainVM()
{
    ScanForDevicesCMD = new RelayCommand(ScanForDevices, CanScanForDevices);
}

public async void ScanForDevices(object obj)
{
    Debug.WriteLine("SCAN STARTED");

    Task task = NetworkPlaces();
    await task;
    Debug.WriteLine("SCAN STOPPED");
}

public Task NetworkPlaces()
{
    ShellNetworkComputers shellNetworkComputers = new ShellNetworkComputers();
    foreach (string snc in shellNetworkComputers)
    {
        Debug.WriteLine(snc);
    }
    return Task.CompletedTask;           
}

CodePudding user response:

You can run synchronous code as a Task.

Change your method to this:

public void NetworkPlaces()
{
    ShellNetworkComputers shellNetworkComputers = new ShellNetworkComputers();
    foreach (string snc in shellNetworkComputers)
    {
        Debug.WriteLine(snc);
    }         
}

And call it like this:

await Task.Run(() => {
    NetworkPlaces();
});
  • Related