实现异步方法

时间:2009-05-13 11:56:19

标签: c# asynchronous

我希望在类库中实现方法的同步和异步版本。目前我已经这样做了,以便Async方法触发一个新线程并进行处理。要确定操作是否已完成,用户应轮询属性以查看它是否已完成。

我想改进它,我认为使用某种形式的异步回调或结果会更好,但我不确定如何实现它,或者,如果确实有必要的话。有人可以提供任何建议吗?

3 个答案:

答案 0 :(得分:6)

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();
    });
}

用法:

    Queue( () => { Console.WriteLine("doing work"); }, 
           () => { Console.WriteLine("work was done!"); } );

答案 1 :(得分:2)

您可以使用回调方法而不是轮询。 在AsyncCallback

上查看我的答案

<强>编辑:

使用具有回调的自己的异步委托的FileCopy示例:

    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
        }
    }

您可以将其命名为:

AsyncFileCopier.AsynFileCopy("abc.txt", "xyz.txt");

答案 2 :(得分:0)

异步代理可能是另一种选择。

在MSDN上阅读Asynchronous Programming Using Delegates

相关问题