Asynchronous Silverlight WCF callback

为君一笑 提交于 2019-12-24 23:12:16

问题


I've created my own WCF service and I've successfully been able to talk to it via my Silverlight client. I ran into an interesting problem on my asynchronous callbacks though. When my callback is invoked, I can't update any UI controls with the dreaded invalid cross thread access

Here's what my callback function looks like

    private void GetTimeCallBack( object sender, Talk.ClientBase<IService>.ClientEventArgs e )
    {
        lblDisplay.Text = e.Object.ToString();
    }

A quick google search showed me that I have to do this instead.

private void GetTimeCallBack( object sender, Talk.ClientBase<IService>.ClientEventArgs e )
    {
        Dispatcher.BeginInvoke( () => lblDisplay.Text = e.Object.ToString() );
    }

Now everything works fine, but I wasn't expecting my callback to be running on a different thread. Will I always have to use the Dispatcher class in order to modify anything within my class or is this just limited to UI elements? I've not familiar with the Dispatcher class at all so I'm looking to understand it more.


回答1:


yes.. Checkout the link for more info. I have added Joel's reply to the question below

In Silverlight 2 Beta 2 there was a significant change in the concurrency model used for asynchronous communications. In Beta 1 these type of requests returned on the UI thread. In Beta 2, when you choose to use the BeginGetResponse of the WebRequest you are telling Silverlight to use a worker thread that comes from a thread pool. As a result, you can NOT update any user interface elements on the UI thread. Using Dispatcher.BeginInvoke is a way to get a method to fire back on the UIThread from this threadpool thead. Any interaction with UIelements from the Async callback will throw a cross thread exception.



来源:https://stackoverflow.com/questions/2521309/asynchronous-silverlight-wcf-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!