Jump to content

Search the Community

Showing results for tags 'promise'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Delphi Questions and Answers
    • Algorithms, Data Structures and Class Design
    • VCL
    • FMX
    • RTL and Delphi Object Pascal
    • Databases
    • Network, Cloud and Web
    • Windows API
    • Cross-platform
    • Delphi IDE and APIs
    • General Help
    • Delphi Third-Party
  • C++Builder Questions and Answers
    • General Help
  • General Discussions
    • Embarcadero Lounge
    • Tips / Blogs / Tutorials / Videos
    • Job Opportunities / Coder for Hire
    • I made this
  • Software Development
    • Project Planning and -Management
    • Software Testing and Quality Assurance
  • Community
    • Community Management

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Delphi-Version

Found 1 result

  1. Delphi Async Helpers with TFuture<T>: This demo project provides a clean and safe way to perform background operations in Delphi using TTask and TFuture<T>, with a focus on keeping the UI responsive and preventing memory leaks. πŸ“¦ What's Inside API.Helpers.pas: A generic async helper unit Main.View.pas: A VCL form demonstrating good and bad usage of futures and background tasks. πŸ”§ Helper Static Class: TSimpleFuture<T> A simple abstraction over TTask.Future<T> and TTask.Run to make async coding easier. type TConstProc<T> = reference to procedure (const Arg1: T); TSimpleFuture<T> = class class procedure Run(const aQuery: TFunc<T>; const aReply: TConstProc<T>); static; class procedure RunFuture(const aQuery: TFunc<T>; const aReply: TConstProc<T>); static; end; πŸ–Ό Demo Form: `Main.View.pas` The form includes buttons that demonstrate the following patterns: βœ… Correct Usage (Non-Blocking): `πŸ’ͺ BtnStartWithHelper`: TSimpleFuture<string>.RunFuture(function: string begin Sleep(2000); Result := TimeToStr(Now) + ' βœ… ΨͺΩ… Ψ§Ω„ΨͺΩ†ΩΩŠΨ°'; end, LogReply); > βœ… Background-safe > βœ… Memory-safe > βœ… Beginner-friendly ⚠️ Incorrect Usage (`BtnWrongUse`): var LFuture := TTask.Future<string>(...); LogReply(LFuture.Value); // ❌ Blocks the main thread! > ❌ This freezes the UI and defeats the purpose of async programming. βœ… Safe Manual Usage(`BtnWaitOutsideMainThread`): LFuture := TTask.Future<Integer>(...); TTask.Run( procedure begin var LValue := LFuture.Value; // Block or wait inside background thread. TThread.Queue(nil, procedure begin LogReply('Result: ' + LValue.ToString); // update UI on main thread LFuture := nil; // release `IFuture<T>` reference to avoid Memory Leak (TCompleteEventWrapper etc of internal thread pool that service the TTask). end); end); > βœ… Keeps UI free. > βœ… Releases `LFuture` to prevent leaks. πŸ§ͺ Simulating `IFuture<T>` with `ITask`(`BtnSimulateIFuture`): var LResult: string; LFuture := TTask.Run(...); TTask.Run(procedure begin LFuture.Wait; // Call wait inside background thread like IFuture<T>.Value does .. TThread.Queue(nil, procedure begin LogReply(LResult); LFuture := nil; // release `IFuture<T>` reference to avoid Memory Leak (TCompleteEventWrapper etc of internal thread pool that service the TTask). end); end); > 🧠 A useful trick for simulating `Future.Value` behavior without using `TFuture<T>`. πŸ” Future Monitoring Pattern(`BtnMonitorSolution`): A more advanced way to ensure task completion: var LFuture := TTask.Future<string>(...); TTask.Run(procedure begin while not (LFuture.Status in [TTaskStatus.Completed, TTaskStatus.Canceled, TTaskStatus.Exception]) do TThread.Sleep(100); // Reduce CPU Usage ..(Check every 100 Millisec). TThread.Queue(nil, procedure begin if LFuture.Status = TTaskStatus.Completed then LogReply(LFuture.Value) else LogReply('Future Failled or Canceled !!'); LFuture := nil; // release `IFuture<T>` reference to avoid Memory Leak (TCompleteEventWrapper etc of internal thread pool that service the TTask). end); end); 🧼 Best Practices (in my opinion now): βœ… Do : - Use `TThread.Queue` to update UI - Use `TFuture.Value` **only from background threads** - Set `LFuture := nil` to release memory ❌ Don’t : - Call `.Value` on the main thread. - Forget to release `IFuture<T>` reference to avoid Memory Leak (TCompleteEventWrapper etc of internal thread pool that service the TTask). - Update UI directly from background threads. 🧰 Requirements: - Delphi XE7+ - VCL application (not mandatory, but my Demo is VCL) - `System.Threading` unit. πŸ“œ License Free to use and modify in any personal or commercial project. 🧠 Design Philosophy: What Future Really Means In general software design, a Future is an abstraction that represents a promise of a result to be available in the future. It is not intended to be synchronously accessed using .Value, especially not from the main thread. ❌ Misconception: Using .Value Is Asynchronous The Future is not designed for synchronous use β€” instead, it should be part of a fully asynchronous programming style, ideally involving a callback mechanism. Calling .Value is essentially a blocking call, which defeats the purpose of using Future in the first place. βœ… The Core Idea Behind Future The essence of the Future abstraction is: πŸ”Ή A promise for a future result without blocking the current thread, preferably using a callback to handle the result when it’s ready. So using .Value is almost equivalent to Task.Wait β€” not a true asynchronous pattern ⚠️ Using .Value on the Main Thread Is Misleading! One of the most common pitfalls developers face with IFuture<T> in Delphi is the assumption that it is meant to be accessed using .Value. In reality, this goes against the very design philosophy of Future in most programming languages. In Delphi, calling .Value internally does something like this: function TFuture<T>.GetValue: T; begin Wait; // β›” This blocks the current thread! Result := FResult; end; So, it's not just about when the computation starts β€” it’s about how you consume the result in a way that doesn't harm the user experience. πŸ”„ Summary .Value = Blocking = like Wait Future's goal = Non-blocking promise, best used with callbacks Using .Value in UI = ❌ Breaks the async model, risks freezing UI Best practice = Use background thread + TThread.Queue for result delivery ## πŸ™Œ Contributions Feel free to open an issue or PR if you want to extend this helper for things like: - Cancellation - Progress reporting - `Future.ContinueWith(...)` chaining. πŸ”§ if you find any Remarks or Suggestions , please Notify me bellow. Thank you for your Time my Friends. My Ready to use Github Repo here.
Γ—