我選擇一些圖像,並將它們加載到BitmapImage的主線程,現在我想將它們保存到SQLSERVER數據庫在另一個線程(BackgroundWorker的),但出現以下錯誤:轉換的BitmapSource以字節數組在另一個線程
調用線程不能訪問此對象,因爲不同的線程擁有它。
注意:目標字段的數據類型是varbinary(最大值)
示例代碼:
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 ---
}
}
}
你能提供代碼嗎? – 2013-05-07 04:37:08
謝謝。我添加了一個示例代碼到我的問題 – 2013-05-07 06:00:41