繁体   English   中英

Windows Phone-httpwebrequest-将ref变量传递给回调

[英]Windows phone - httpwebrequest - passing ref variables to callback

我从Windows Phone应用程序发送HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("myurl"));
request.BeginGetResponse(MyProcessor, request);

这是回调:

public void MyProcessor(IAsyncResult asynchronousResult)
{
     HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
     HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
     using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
     {
          string text = streamReader.ReadToEnd();
          // passing some arguments to special class, that generates ui elements
      }
}

这是生成器类的方法

public static void AddEventTypeToList(some parameters)
{
       Deployment.Current.Dispatcher.BeginInvoke(() =>
       {
             //xaml generating
       });
}            

所以。 我需要使用Dispatcher.BeginInvoke,因为否则我将获得“无效的跨线程访问”。

但。 我还需要传递对某些参数的引用...而且我收到错误消息“您无法使用带有关键字ref的用户参数或匿名方法,lambda表达式或查询表达式中的参数。

该怎么办? 我通常需要使用HttpWebRequest(因为我需要使用状态码并且它对我来说阻止了WebClient),并将对某些ui元素的引用传递给回调中的特殊uigenerator类


我尝试了Mangist答案,但是有一些我认为的错误:

public static void AddEventTypeToList(EventType ev, ListBox mainListBox, ref List<Grid> inds)
{
      Deployment.Current.Dispatcher.BeginInvoke(new Action<EventType, ListBox, List<Grid>>(DoOnUIThread));

}

正在生成:

 public static void DoOnUIThread(EventType ev, ListBox mainListBox, List<Grid> inds)
 {
       Grid gr = new Grid();
       //....
 }

它根本没有达到此方法的断点

我会使用async / await 生活会更轻松...

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("myurl"));
var response = await request.GetResponseAsync();

using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
    string text = streamReader.ReadToEnd();
    // Updating UI is safe. Do it whichever way you want!!!
}

编辑

您也可以使用HttpClient

using (HttpClient client = new HttpClient())
{
    string text = await client.GetStringAsync("myurl");    
    //update UI here
}
public static void DoOnUIThread(some parameters)
{
  // You can use parameters now.  Obviously "some" is not a type, but you would replace this with the type you're using for your parameters.
}

public static void AddEventTypeToList(some parameters)
{
    // Change Action<Type> to use the type of the parameter you want
       Deployment.Current.Dispatcher.BeginInvoke(new Action<some>(DoOnUIThread));
}   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM