VSoft.Awaitable
v0.5.0
นี่เป็นไลบรารีที่ง่ายสำหรับการเรียกใช้ฟังก์ชันแบบอะซิงโครนัส มันเป็น wrapper เหนือ omnithreadlibrary และขึ้นอยู่กับฟังก์ชันการทำงานของตัวเอง Parallel.async
Parallel.async ไม่ได้ให้วิธีง่ายๆในการยกเลิกการโทรและได้รับแจ้งการยกเลิกและไม่อนุญาตให้ส่งคืนผลลัพธ์
รวม vSoft.AwaItable ในประโยคการใช้งานของคุณ
TAsync.Configure<string>(
function ( const cancelToken : ICancellationToken) : string
var
i: Integer;
begin
result := ' Hello ' + value ;
for i := 0 to 2000 do
begin
Sleep( 1 );
// in loops, check the token
if cancelToken.IsCancelled then
exit;
end ;
// where api's can take a handle for cancellation, use the token.handle
WaitForSingleObject(cancelToken.Handle, 5000 );
// any unhandled exceptions here will result in the on exception proc being called (if configured)
// raise Exception.Create('Error Message');
end , token);
)
.OnException(
procedure ( const e : Exception)
begin
Label1.Caption := e.Message;
end )
.OnCancellation(
procedure
begin
// clean up
Label1.Caption := ' Cancelled ' ;
end )
.Await(
procedure ( const value : string)
begin
// use result
Label1.Caption := value ;
end );
คุณยังสามารถส่งคืน IAwaitable<TResult> จากฟังก์ชั่น
function LoadAsyncWithToken ( const token : ICancellationToken; const value : string) : IAwaitable<string>;
begin
// configure our async call and return the IAwaitable<string>
result := TAsync.Configure<string>(
function( const cancelToken : ICancellationToken) : string
begin
// .... do some long running thing
result := ' Hello ' + value ;
end , token);
end ;
// for when there is no result to return
function RunIt ( const token : ICancellationToken; const value : string) : IAwaitable;
begin
// configure our async call and return the IAwaitable<string>
result := TAsync.Configure(
procedure( const cancelToken : ICancellationToken)
begin
// .... do some long running thing
end , token);
end ;
procedure UseIt ;
begin
LoadAsyncWithToken( ' param ' , FTokenSource.Token)
.OnException(
procedure ( const e : Exception)
begin
Label1.Caption := e.Message;
end )
.OnCancellation(
procedure
begin
// clean up
Label1.Caption := ' Cancelled ' ;
end )
.Await(
procedure ( const value : string)
begin
// use result
Label1.Caption := value ;
end );
RunIt( ' param ' , FTokenSource.Token)
.OnException(
procedure ( const e : Exception)
begin
Label1.Caption := e.Message;
end )
.OnCancellation(
procedure
begin
// clean up
Label1.Caption := ' Cancelled ' ;
end )
.Await(
procedure
begin
// use result
Label1.Caption := ' Done ' ;
end );
โปรดทราบว่าการรอคอยจริงเรียกใช้ฟังก์ชัน async นอกจากนี้ยังมี overload to tasync.configure ที่ไม่ใช้โทเค็นการยกเลิกเมื่อคุณไม่จำเป็นต้องยกเลิก