Tamara Caligari
Tamara Caligari

Reputation: 509

C# wait for task to complete

I have a list of methods to execute and some of them are async methods and they take a while to complete. However I need these tasks to finish before the program moves on to the next task as it is doing at the moment because old data is being shown like this.

Any tips on how to do this? These are my tasks. I need the first three tasks to complete their processing before the last two execute.

public MainPage()
{
    this.InitializeComponent();
    getTemp();
    data = new initialData();            

    SetLiveTile();
    liveTile();           
}

PS: This is for a windows 8 metro app

The code for the getTemp() is the following. My problem is that I need the value from this method before I execute the rest of the methods but before the value is obtained, the program goes on to execute the SetLiveTile and liveTile methods.

 public async void getTemp()
 {
     var weatherService = new WeatherService.GlobalWeatherSoapClient();
     var result = await weatherService.GetWeatherAsync("", "Malta");

     XmlDocument doc = new XmlDocument();

     doc.LoadXml(result);

     int pos = doc.InnerText.IndexOf(" F");
     string rem = doc.InnerText.Remove(0, pos + 4);
     string weather = rem.Substring(0, 2);

     temp = int.Parse(weather);
}

PS: temp is a global variable

Upvotes: 0

Views: 2056

Answers (3)

clausc
clausc

Reputation: 166

You may also want to check to Barrier class: http://msdn.microsoft.com/en-us/library/dd537615(v=vs.110).aspx

Upvotes: 0

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15138

I really don't know the events in a Windows Store App, but in Windows Forms you could add an async event handler on load, for example - say that we have these 3 methods that take some time to finish:

private Task DoWork() {
    return Task.Delay(3000);
}

private Task DoSomeMoreWork() {
    return Task.Delay(5000);
}

private Task DoEvenMoreWork() {
    return Task.Delay(7000);
}

private async void MyForm_Load(object sender, EventArgs e) {
    // this will take 7 seconds it will execute all the methods at the same time and will resume when all are completed
    await Task.WhenAll(DoWork(), DoSomeMoreWork(), DoEvenMoreWork());

    // will be here when all the methods are done executing
}

I hope this gives you an idea at least.

Upvotes: 0

MrCakePie
MrCakePie

Reputation: 11

I don't know which of your tasks is being run on a different thread, but theoretically when you have a thread, and you want to do something AFTER it finished performing its task, you use the thread.join() method (much like in Java).

Upvotes: 1

Related Questions