Reputation:
How does a called function let the calling function know that he's done with all it's processing?
myFunction1(){
myFunction2();
}
myFunction2(DownloadStringCompletedEventHandler callback){
// Calls a web service and updates local files
}
myFunction2Returned(object sender, DownloadStringCompletedEventArgs e){
}
Start the whole call like this:
myFunction1();
// Continue processing here...
Now what I want to know is, if I call myFunction1()
, how can you wait untill everything in myFunction2()
has finished before you carry on with your processing? (that being whatever lies beyond the 'continue processing here...' comment).
The problem is that after I call myFuntion1()
my code after that tries to read files that rely on myFunction2()
to have completed it's web service call and completely written the needed files to disk.
I hope all this makes sense, was pretty difficult getting the wording right for the question to make sense.
Upvotes: 0
Views: 149
Reputation: 28345
You should use some tasks techniques for this, something like this:
static void SimpleNestedTask()
{
var parent = Task.Factory.StartNew(() =>
{
// myFunction1 code here;
Console.WriteLine("Outer task executing.");
var child = Task.Factory.StartNew((t) =>
{
// myFunction2 code here
// Calls a web service and updates local files
Console.WriteLine("Nested task completing.");
}, TaskCreationOptions.AttachedToParent | TaskCreationOptions.LongRunning);
});
parent.Wait();
Console.WriteLine("Outer has completed.");
}
Upvotes: 1
Reputation: 25204
You need to use async and await. You can write a function like this:
private async void SomeFunction()
{
// Do something
await SomeOtherFunction();
// Do something else
}
As is in your case, this is especially useful for things like web service access where you don't have control over the processing of the other function. The keywords here are async
and await
which signal that the function is going to involve asynchronous programming.
Note that this syntax is relatively new (C#5), but since you didn't tag any specific version of .NET in your question I figured I would give you the latest and greatest ;).
Upvotes: 2