Show: Object Pascal C++
Display Preferences

Using TTask.IFuture from the Parallel Programming Library

From Appmethod Topics
Jump to: navigation, search

Go Up to Using the Parallel Programming Library

IFuture implements TTask to launch a function that returns a specific type. Instances of IFuture are returned by the TTask.Future<T>, where the type parameter, T, represents the return type. Using an instance of IFuture, you can calculate something or run some query and at the same time you can do other tasks, getting the value when you want via IFuture.Value. At this point, if the value is not completed yet, it blocks the current waiting for this value to be calculated. This allows you to prioritize code blocks to run in the order you want, but still ensure you get the value at the point you need it.

Object Pascal:

First, declare your instance of IFuture<T>. In this snippet we use it to store a String.

  public
    { Public declarations }
    FutureString: IFuture<string>;

The implementation that pases as an anonymous method to TTask.Future<T>:

FutureString:= TTask.Future<string>(
function:string
  begin
   {Some calculation that takes time}
    Sleep(3000);
    Result:='Hello ' + Random(42).ToString;
  end);

You can obtain the calculated value by calling IFuture.Value:

MyString := FutureString.Value;

C++:

First, declare your instance of IFuture<T>. In this snippet we use it to store a String. You also need to declare the method that holds the implementation of the TTask.Future<T> handler method.

public:		// User declarations
	System::DelphiInterface<IFuture__1<System::String> > FutureString;
	System::String __fastcall FutureHandler(TObject* Sender);

The implementation of the TTask.Future<T> handler method and the call to that method:

System::String __fastcall TForm1::FutureHandler(TObject* Sender){
  // Some calculation that takes time
  Sleep(3000);
  return System::String str = System::String().sprintf(L"Hello %d", Random(42));
}
FutureString = TTask::Future<System::String>(0, this->FutureHandler);

You can obtain the calculated value by calling IFuture.Value:

MyString = FutureString->Value;

See Also

Personal tools
In other languages