首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF STA线程错误

WPF STA线程错误
EN

Stack Overflow用户
提问于 2011-10-17 21:13:05
回答 2查看 2.9K关注 0票数 0

我正在遵循这个线程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声明了调用线程的状态,我的代码如下:

代码语言:javascript
复制
    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;  
    }

有人能帮帮忙吗?

非常感谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-17 21:26:59

你需要调用MainThread中的每一个UI操作,我猜你的UpdateItem方法不会在MainThread中被调用,因此你会得到这个异常。

我会改变两件事:

首先,使用BackgroundWorker类,它使得WPF中的这种异步操作变得非常简单。

其次,如果你有另一个线程(后台工作者或自定义线程),你总是必须将每个UI操作Dispatch到主线程中。

票数 0
EN

Stack Overflow用户

发布于 2011-10-17 22:45:14

你可以试着在下面包装你的代码,但是这是一个肮脏的解决方案。

代码语言:javascript
复制
MyUIElement.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{

    //your code here

}));

如果MyUIElement是你最上面的窗口就好了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7794258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档