用Reactive Extension实现异步方法超时的操作
Action action = new Action(() =>
{
Thread.Sleep(5000);
});
var Async = Observable.FromAsyncPattern(action.BeginInvoke, action.EndInvoke);
Observable.Timeout(Async.Invoke(), DateTimeOffset.Now.AddSeconds(3)).ObserveOnDispatcher().Subscribe(it =>
{
MessageBox.Show("执行完毕");
}, ex =>
{
MessageBox.Show("超时");
});
{
Thread.Sleep(5000);
});
var Async = Observable.FromAsyncPattern(action.BeginInvoke, action.EndInvoke);
Observable.Timeout(Async.Invoke(), DateTimeOffset.Now.AddSeconds(3)).ObserveOnDispatcher().Subscribe(it =>
{
MessageBox.Show("执行完毕");
}, ex =>
{
MessageBox.Show("超时");
});