使用 Linq to SQL 和 Rx 处理数据库连接异常
我正在尝试学习如何最好地使用 Reactive Extensions 库,并设置了简单的测试 WPF 应用程序来查看日志记录数据库表。在 ViewModel 类中,我使用 Linq to Sql DataContext
中的前 100 个日志条目填充 ObservableCollection
,并且我尝试使用 Rx 来保持 UI 响应。
除非数据库不可用,否则以下代码片段将起作用,此时应用程序会引发异常并崩溃。哪里是处理数据库连接异常的最佳位置?为什么观察者的 OnError
方法不处理这些异常?
ObservableCollection<LogEntry> _logEntries = new ObservableCollection<LogEntry>();
DataContext dataContext = new DataContext( "connection string" );
(from e in dataContext.LogEntries
select e).Take( 100 ).ToObservable()
.SubscribeOn( Scheduler.ThreadPool )
.ObserveOnDispatcher()
.Subscribe( _logEntries.Add, ex => System.Diagnostics.Debug.WriteLine( ex.ToString() ) );
I am trying learn how to best use the Reactive Extensions library and have set up simple test WPF application to view a logging database table. In a ViewModel class I am populating an ObservableCollection
with the first 100 log entries from a Linq to Sql DataContext
and I'm trying to use Rx to keep the UI responsive.
The following snippet works unless the database is unavailable at which point the app throws an exception and crashes. Where would be the best place to handle database connection exceptions and why are they not handled by the OnError
method of the Observer?
ObservableCollection<LogEntry> _logEntries = new ObservableCollection<LogEntry>();
DataContext dataContext = new DataContext( "connection string" );
(from e in dataContext.LogEntries
select e).Take( 100 ).ToObservable()
.SubscribeOn( Scheduler.ThreadPool )
.ObserveOnDispatcher()
.Subscribe( _logEntries.Add, ex => System.Diagnostics.Debug.WriteLine( ex.ToString() ) );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这个而不是 ToObservable:
不过,一般来说,这不是 Rx 的一个很好的用途,因为数据源不太容易 Rx'ify - 事实上,代码将在 UI 线程上执行大部分工作,发送它发送到随机工作线程,然后将其发送回来(即完全浪费了工作)。 Task + Dispatcher.BeginInvoke 可能更适合您。
Try this instead of ToObservable:
In general though, this isn't a great use of Rx since the data source isn't very easy to Rx'ify - in fact, the code will execute most of the work on the UI thread, send it out to random worker threads, then send it back (i.e. completely wasted work). Task + Dispatcher.BeginInvoke might suit you better here.