i select some image and load them into bitmapimage in the main thread,now i want to save them to sqlserver database in another thread ( BackgroundWorker),But the following error occurs:
The calling thread cannot access this object because a different thread owns it.
Notice : The DataType of target field is varbinary(max)
Sample Code:
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 ---
}
}
}