【发布时间】:2011-10-17 13:13:05
【问题描述】:
我正在关注这个线程上给出的代码C# Async WebRequests: Perform Action When All Requests Are Completed
在我的 WPF 应用程序中,我需要从服务器异步下载图像。但是我收到以下错误
The calling thread must be STA, because many UI components require this.
可能是因为我在主线程上进行 UI 更新?我还向STA声明了调用线程的状态,我的代码如下:
private void FixedDocument_Loaded(object sender, RoutedEventArgs e)
{
Thread t = new Thread(new ThreadStart(AsyncLoadImages));
t.IsBackground = true;
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
}
private void AsyncLoadImages()
{
foreach (string resFile in resFiles)
{
string imageuri = @"http://www.example.com/image.jpg";
WebRequest request = HttpWebRequest.Create(imageuri);
request.Method = "GET";
object data = new object();
RequestState state = new RequestState(request, data);
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(UpdateItem), state);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(ScanTimeoutCallback), state, (30 * 1000), true);
}
}
private static void ScanTimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)state;
if (reqState != null)
{
reqState.Request.Abort();
}
Console.WriteLine("aborted- timeout");
}
}
private void UpdateItem(IAsyncResult result)
{
RequestState state = (RequestState)result.AsyncState;
WebRequest request = (WebRequest)state.Request;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = response.GetResponseStream();
bi.EndInit();
Image i = new Image(); //hitting the error at this line
i.Source = bi;
}
有人可以帮忙吗?
非常感谢
【问题讨论】:
-
另外,调用
t.Join()会阻塞UI线程 -
UpdateItem 在线程池线程上运行,它们始终是 MTA。但是将工作线程设置为 STA 无论如何也无济于事,这是错误的单线程单元。您必须使用 Dispatcher.Begin/Invoke() 来创建图像。
标签: wpf multithreading asynchronous httpwebrequest