我选择了一些图像并将它们加载到主线程中的位图图像中,现在我想将它们保存到另一个线程(BackgroundWorker)中的 sqlserver 数据库中,但出现以下错误:
调用线程无法访问此对象,因为不同的线程拥有它。
注意:目标字段的 DataType 是 varbinary(max)
示例代码:
class Class1
{
private List<BitmapSource> Items;
public Class1()
{
this.Items = new List<BitmapSource>();
}
public void AddItem(BitmapSource bs)
{
this.Items.Add(bs);
}
public void Save()
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += bw_DoWork;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
bw.RunWorkerAsync(this.Items);
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
throw new NotImplementedException();
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
MyBLL bl = new MyBLL();
bl.Save(e.Argument as List<BitmapSource>);
}
}
public class MyBLL
{
public byte[] ConvertBitmapSourceToByteArray(BitmapSource BS)
{
if (BS == null)
{
return new byte[] { };
}
using (MemoryStream ms = new MemoryStream())
{
JpegBitmapEncoder jbe = new JpegBitmapEncoder();
jbe.Frames.Add(BitmapFrame.Create(BS.Clone()));
jbe.Save(ms);
return ms.GetBuffer();
}
}
public void Save(List<BitmapSource> _items)
{
foreach (BitmapSource item in _items)
{
--- insert ConvertBitmapSourceToByteArray(item) to DataBase ---
}
}
}