我想在类库中实现方法的同步和异步版本.目前我已经这样做了,以便Async方法触发一个新线程并进行处理.要确定操作是否已完成,用户应轮询属性以查看其是否已完成.
我想改进它,我认为使用某种形式的异步回调或结果会更好,但我不确定如何实现它,或者,如果确实有必要的话.有人可以提供任何建议吗?
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();
});
}
Run Code Online (Sandbox Code Playgroud)
用法:
Queue( () => { Console.WriteLine("doing work"); },
() => { Console.WriteLine("work was done!"); } );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1765 次 |
| 最近记录: |