UnauthorizedAccessException:Silverlight应用程序中的无线跨线程访问(XAML/C#)

Pol*_*ing 12 c# silverlight

相对较新的C#,并希望尝试使用它的一些第三方Web服务API.

这是XAML代码

    <Grid x:Name="ContentGrid" Grid.Row="1">
        <StackPanel>
            <Button Content="Load Data" Click="Button_Click" />
            <TextBlock x:Name="TwitterPost" Text="Here I am"/>
        </StackPanel>
    </Grid>
Run Code Online (Sandbox Code Playgroud)

这是C#代码

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.twitter.com/1/users/show/keykoo.xml");
        request.Method = "GET";

        request.BeginGetResponse(new AsyncCallback(twitterCallback), request);
    }

    private void twitterCallback(IAsyncResult result)
    {
        HttpWebRequest request = (HttpWebRequest)result.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
        TextReader reader = new StreamReader(response.GetResponseStream());
        string strResponse = reader.ReadToEnd();

        Console.WriteLine("I am done here");
        TwitterPost.Text = "hello there";
    }
Run Code Online (Sandbox Code Playgroud)

我猜这是因为回调在一个单独的线程上执行而不是UI?在C#中处理这些类型的交互的正常流程是什么?

谢谢.

Ste*_*ock 29

A useful way to get easy cross thread access with the CheckAccess call is to wrap up a utility method in a static class - e.g.

public static class UIThread
{
    private static readonly Dispatcher Dispatcher;

    static UIThread()
    {
        // Store a reference to the current Dispatcher once per application
        Dispatcher = Deployment.Current.Dispatcher;
    }

    /// <summary>
    ///   Invokes the given action on the UI thread - if the current thread is the UI thread this will just invoke the action directly on
    ///   the current thread so it can be safely called without the calling method being aware of which thread it is on.
    /// </summary>
    public static void Invoke(Action action)
    {
        if (Dispatcher.CheckAccess())
            action.Invoke();
        else
            Dispatcher.BeginInvoke(action);
    }
}
Run Code Online (Sandbox Code Playgroud)

then you can wrap any calls that update the UI where you may be on a background thread like so:

private void twitterCallback(IAsyncResult result)   
{   
        HttpWebRequest request = (HttpWebRequest)result.AsyncState;   
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);   
        TextReader reader = new StreamReader(response.GetResponseStream());   
        string strResponse = reader.ReadToEnd();   

        UIThread.Invoke(() => TwitterPost.Text = "hello there");
}   
Run Code Online (Sandbox Code Playgroud)

This way you don't have to know whether you are on a background thread or not and it avoids the overhead of adding methods to every control to check this.


Ane*_*ero 1

正如您所猜测的,silverlight 在单独的线程上异步执行所有 Web 请求,以避免冻结 UI。

要将消息分派到 UI 线程,您可以使用Deployment.Current.Dispatcher.BeginInvoke(delegate, object[])方法。