I have a method where i 开发者_如何学JAVAwant to return Task and the task finish once some internal condition is true. so the code would be:
public Task<Result> Method(int numberOfAggregats){
return new Task<Result>(() => "return result once
aggregated information > numberOfAggregates");
}
Is there some way to do this without a loop that eats all the cpu or a Thread.Sleep?
some more information: i have a class who´s purpose is to aggregate information coming in through wcf queries into the server. this is the class containing the "Method" method. this method is beeing called by the ui, as well as background works, who need the aggregated information.
until now we were passing in a callback action into method, which would be called once all the information was there. The idea behind returning Task is to get rid of the callbacks, since they complicate the code in the depending modules.
Use AutoResetEvent:
System.Threading.AutoResetEvent _notifier = new AutoResetEvent(false);
At the waiting task call
_notifier.WaitOne();
so it will blocked until receive a signal.When internal condition becomes true call
_notifier.Set();
to signal the waiting task to finish.
http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx Try this it's a conditional variable lock. Once the task is done you can signal the variable and that will begin execution.
Perhaps the IAsynchResult pattern is what you're looking for
However since you're using the TPL a continuation might make more sense
精彩评论