SQL Server Compact 3.5在后台进程中随机出现异常
本文关键字:随机 异常 后台进程 Server Compact SQL | 更新日期: 2023-09-27 18:28:30
当我移动到SQL Server Compact 3.5时,它会在后台运行的线程中产生异常,每次都会给我不同的异常,如下所示。。
-
An item with the same key has already been added.
-
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
-
Attempted to read Data when Datareader is closed
这对我来说很烦人,因为它突然停止了我的应用程序。。
请注意,当我的后台工作程序或任务调度程序在我的应用程序中运行时,就会发生这种情况,否则应用程序工作正常。
我不知道我是做错了还是仅仅因为SQL Server Compact 3.5
能帮我解决问题吗?
谢谢。。
编辑使用工作单元。
在主线程中,我正在从存储库中收集200条记录
UnitOfWork _uow;
ObservableCollection<ViewModel> Colloection = new ObservableCollection<ViewModel>;
ObservableCollection<ViewModel> AllColloection = new ObservableCollection<ViewModel>;
public Class()
{
Colloection = _uow.Contacts.Getall().Select(s=> new ViewModel(s,_uow)).Take(200).ToList();
}
在后台工作者
AllColloection =_uow.Contacts.Getall().Select(s=> new ViewModel(s,_uow)).ToList();
在收集AllCollection时,它给了我的例外
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
最初我想显示200条记录,当用户点击next时,我将从Allcollection收集接下来的200条记录。
看起来您在不同的线程之间共享ADO.NET对象(连接、命令、读取器等)而没有同步。
要么在代码中添加一些同步:
private readonly _uowLock;
public Class()
{
_uowLock = new object();
// run any background threads
// loading data in main thread
LoadCollection();
}
private void LoadCollection()
{
// obtain lock
lock (_uowLock)
{
Collection = _uow.Contacts.Getall().Select(s=> new ViewModel(s,_uow)).Take(200).ToList();
}
}
// this should be called from background worker
private void LoadAllCollection()
{
// obtain lock
lock (_uowLock)
{
AllColloection =_uow.Contacts.Getall().Select(s=> new ViewModel(s,_uow)).ToList();
}
}
,或者不在线程之间共享ADO.NET对象-它们不是线程安全的:
public Class()
{
// run any background threads
// loading data in main thread
LoadCollection();
}
private void LoadCollection()
{
Collection = new UnitOfWork().Contacts.Getall().Select(s=> new ViewModel(s,_uow)).Take(200).ToList();
}
// this should be called from background worker
private void LoadAllCollection()
{
AllColloection = new UnitOfWork().Contacts.Getall().Select(s=> new ViewModel(s,_uow)).ToList();
}