我正在遵循这个线程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;
}有人能帮帮忙吗?
非常感谢
发布于 2011-10-17 21:26:59
你需要调用MainThread中的每一个UI操作,我猜你的UpdateItem方法不会在MainThread中被调用,因此你会得到这个异常。
我会改变两件事:
首先,使用BackgroundWorker类,它使得WPF中的这种异步操作变得非常简单。
其次,如果你有另一个线程(后台工作者或自定义线程),你总是必须将每个UI操作Dispatch到主线程中。
发布于 2011-10-17 22:45:14
你可以试着在下面包装你的代码,但是这是一个肮脏的解决方案。
MyUIElement.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
//your code here
}));如果MyUIElement是你最上面的窗口就好了。
https://stackoverflow.com/questions/7794258
复制相似问题