Asynchronous Method Implementation
I'm looking to implement a synchronous and asynchronous version of a method in a class library. I currently do this to have the Async method start a new thread and process it. To determine if an action has completed, the user must poll the property to see if it has completed.
I would like to improve it, I think it would be better to use some form of callback or Async result, but I'm not sure how to implement this, or if it is really necessary. Can anyone suggest any advice?
a source to share
public static void Queue(Action action, Action done) {
ThreadPool.QueueUserWorkItem(_ =>
{
try {
action();
}
catch (ThreadAbortException) { /* dont report on this */ }
catch (Exception ex) {
Debug.Assert(false, "Async thread crashed! This must be fixed. " + ex.ToString());
}
// note: this will not be called if the thread is aborted
if (done != null) done();
});
}
Using:
Queue( () => { Console.WriteLine("doing work"); },
() => { Console.WriteLine("work was done!"); } );
a source to share
Instead of polling, you can use a callback method. Check out my answer on AsyncCallback
Edited:
FileCopy example using native async delegates with callback:
public class AsyncFileCopier
{
public delegate void FileCopyDelegate(string sourceFile, string destFile);
public static void AsynFileCopy(string sourceFile, string destFile)
{
FileCopyDelegate del = new FileCopyDelegate(FileCopy);
IAsyncResult result = del.BeginInvoke(sourceFile, destFile, CallBackAfterFileCopied, null);
}
public static void FileCopy(string sourceFile, string destFile)
{
// Code to copy the file
}
public static void CallBackAfterFileCopied(IAsyncResult result)
{
// Code to be run after file copy is done
}
}
You can call it like:
AsyncFileCopier.AsynFileCopy("abc.txt", "xyz.txt");
a source to share
Asynchronous delegates can be another option.
Read about Asynchronous Programming Using Delegates on MSDN
a source to share