31-03-2026, 09:08 AM
كود :
unit Async.Fluent;
interface
uses
System.SysUtils, System.Threading, System.Classes;
type
IAsyncOperation<T> = interface
['{F2C3D4E5-A1B2-C3D4-E5F6-AABBCCDDEEFF}']
function OnSuccess(Proc: TProc<T>): IAsyncOperation<T>;
function OnError(Proc: TProc<Exception>): IAsyncOperation<T>;
end;
TAsyncOperation<T> = class(TInterfacedObject, IAsyncOperation<T>)
private
FFunc: TFunc<T>;
FOnSuccess: TProc<T>;
FOnError: TProc<Exception>;
FSelfReference: IAsyncOperation<T>;
procedure Execute;
public
constructor Create(AFunc: TFunc<T>);
function OnSuccess(Proc: TProc<T>): IAsyncOperation<T>;
function OnError(Proc: TProc<Exception>): IAsyncOperation<T>;
class function Run(AFunc: TFunc<T>): IAsyncOperation<T>;
end;
TAsync = class
public
class function Call<T>(Func: TFunc<T>): IAsyncOperation<T>;
end;
implementation
{ TAsyncOperation<T> }
constructor TAsyncOperation<T>.Create(AFunc: TFunc<T>);
begin
inherited Create;
FFunc := AFunc;
end;
class function TAsyncOperation<T>.Run(AFunc: TFunc<T>): IAsyncOperation<T>;
var
Op: TAsyncOperation<T>;
begin
Op := TAsyncOperation<T>.Create(AFunc);
Result := Op;
// نضمن بقاء الكائن في الذاكرة حتى ينتهي الخيط
Op.FSelfReference := Result;
// تشغيل الخيط بعد ضمان اكتمال بناء الواجهة تماماً
TThread.ForceQueue(nil, procedure
begin
Op.Execute;
end);
end;
procedure TAsyncOperation<T>.Execute;
begin
TTask.Run(procedure
var
LResult: T;
begin
try
// تنفيذ الدالة المطلوبة
LResult := FFunc();
// العودة للخيط الرئيسي للنتائج
TThread.Queue(nil, procedure
begin
try
if Assigned(FOnSuccess) then
FOnSuccess(LResult);
finally
FSelfReference := nil; // التدمير الذاتي الآمن
end;
end);
except
on E: Exception do
begin
TThread.Queue(nil, procedure
var
LExc: Exception;
begin
try
if Assigned(FOnError) then
FOnError(E);
finally
FSelfReference := nil; // التدمير الذاتي الآمن
end;
end);
end;
end;
end);
end;
function TAsyncOperation<T>.OnSuccess(Proc: TProc<T>): IAsyncOperation<T>;
begin
FOnSuccess := Proc;
Result := Self;
end;
function TAsyncOperation<T>.OnError(Proc: TProc<Exception>): IAsyncOperation<T>;
begin
FOnError := Proc;
Result := Self;
end;
{ TAsync }
class function TAsync.Call<T>(Func: TFunc<T>): IAsyncOperation<T>;
begin
// نستخدم دالة Run لضمان تسلسل صحيح للذاكرة
Result := TAsyncOperation<T>.Run(Func);
end;
end.بنفس الطريقة زر ولايبيل واكتب فيه
كود :
TAsync.Call<string>(function: string
begin
Sleep(2000);
Result := 'تمت العملية بنجاح';
end)
.OnSuccess(procedure(Val: string)
begin
ShowMessage(Val);
end)
.OnError(procedure(E: Exception)
begin
ShowMessage('خطأ: ' + E.Message);
end);لاحظ كيف ان الكود صار اكثر تنظيما وفهما وابسط بكثير
ولكن هذه مجرد عملية واحدة ماذا لو اردنا عملية تنتظر عملية اخرى وهو اساس موضوعنا
طبعا تستطيع استخدام نفس الوحدة وتضع علمية بداخل عملية اخرى ولكنه ليس الاسلوب الامثل وسوف نكمل
وهنا نحتاج الى وحدة مثل
إذا رأيت منتجاً مجانياً فأعلم بأنك أنت السّلعة


