AsyncWindowsClipboard is thread-safe, asynchronous windows clipboard service with retry strategy for .NET
- It gives async/await syntax to communicate with Windows clipboard API's.
- It is thread safe.
- It gives lower (binary) level read & write access to strings in clipboard than .NET implementation.
- Implements retry strategies to connect to the clipboard when it's locked.
AsyncClipboardService
ensures that:
- The
Task
s for the communication always run in the same thread which makes the communication thread safe. - The thread is in Single Thread Apartment (STA) model. WPF & Windows Forms uses COM interop to communicate with clipboard in STA state. Running the thread in same apartment state ensures that the library functions well. Read more at MSDN 1, 2, 3.
- Implements retry strategy to ensure clipboard operation ends successfully.
You can use a new instance of WindowsClipboardService
to retrieve data. It's okay to use the instance from different threads.
var clipboardService = new WindowsClipboardService();
await clipboardService.SetTextAsync("Hello world"); // Sets the text
var data = await clipboardService.GetTextAsync(); // Reads "Hello world"
However, it's recommended to use WindowsClipboardService
with a timeout strategy, as it'll then wait (in a spinning state) for the thread that blocks the windows api instead of failing. You can activate the timeout strategy by setting it in the constructor:
var clipboardService = new WindowsClipboardService(timeout:TimeSpan.FromMilliseconds(200));
// or via its property
var clipboardService = new ClipboardService { Timeout = TimeSpan.FromMilliseconds(200) };
Fork β Modify β Pull request
What's supported so far are :
- Text read + write
- Unicode bytes read + write
- File drop list read + write
Missing (contributions are welcomed):
- Audio read + write
- Image read + write
For reference implementations, take look at Readers and Writers.