如何在后台同步下载图像?

时间:2011-11-25 08:37:20

标签: c# silverlight windows-phone-7 silverlight-4.0

我有一个后台工作程序,用于从Web服务器获取一些数据。 它也需要下载一些图像(png或jpg)。 但每次我尝试在后台工作线程中创建BitmapImage或WriteableBitmap我都会得到无效的跨线程访问 是否有可能在后台加载图像而不是UI线程?

2 个答案:

答案 0 :(得分:4)

使用它会对你有用。

Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //write here whatever you want to update on screen.
                    textblock.Text = "text changed";
                    // just like this line changed the text of a textblock
                });

如果无效,请粘贴您的代码。

答案 1 :(得分:1)

在BackgroundWorker的DoWork方法中,您无法访问在主线程中创建的控件,但在该方法中,您可以将下载的图像传递给RunWorkerCompleted事件方法,因为此事件在线程上运行你创建了BackgroundWorker(在大多数情况下它是主线程)。

BackgroundWorker backgroundworker = new BackgroundWorker();
backgroundworker.DoWork += new DoWorkEventHandler(backgroundworker_DoWork);
backgroundworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundworker_RunWorkerCompleted);


static void backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //download image and make Image class instance
    e.Result = //assign your image here
}

static void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
{
    Image i = (e.Result as Image);
    //assign image to your control
}