【问题标题】:How to get main thread to wait on completion of StreamReader in a different class如何让主线程等待不同类中的 StreamReader 完成
【发布时间】:2013-04-01 11:56:13
【问题描述】:

我目前正在开发一个应用程序,但对 wp7 开发来说相当新,我的主进程调用另一个使用 StreamReader 读取网页内容并分配变量的类。我遇到的问题是主进程试图在变量被赋值之前使用它们。有什么办法可以让主进程等到 StreamReader 完成

在我的主线程中:

 locationDetails = new LocationResults();
 locationDetails.getResults(addressDetails);

然后在 LocationResults 类中

public void getResults(String address)
    {
        String addy, tmp;
        if (address[0] == '+')
        {
            tmp = address.Substring(1);
            addy = baseAddress + tmp + "&sensor=false";
        }
        else
            addy = baseAddress + address + "&sensor=false";

        WebClient webClient = new WebClient();
        webClient.OpenReadAsync(new Uri(addy));
        webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);

    }

    void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        String tmp;
        var reader = new StreamReader(e.Result);
        tmp = reader.ReadToEnd().ToString();
        results = tmp;
    }

【问题讨论】:

    标签: windows-phone-7 concurrency webclient iostream


    【解决方案1】:

    自从我使用 WP 7 和 .NET 以来已经有很长时间了,但我认为以下方法可能会有所帮助:

    1. 使用任务并行库执行与主线程异步的整个 getResult-Procedure。
    2. 在任务中同步使用WebClient,然后返回读取的数据。
    3. 通过http://msdn.microsoft.com/en-us/library/hh194793.aspx 指定一个Continuation 操作并传递主线程的TaskScheduler 实例,以便同步。
    4. 将影响结果的主线程代码放在您的继续操作中。

    编辑: 我猜代码应该是这样的:

    Task.Factory.StartNew((adr)-> InvokeGetResult(adr as string), addressDetails)
       .ContinueWith((data) -> HandleDataSynchronousToMainThread(data),
          TaskScheduler.Current);
    

    但再次强调:距离我编写最后一个 .NET 代码已经很长时间了......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2012-07-22
      • 2021-08-10
      • 2010-12-26
      • 2011-06-05
      • 2016-04-11
      • 1970-01-01
      相关资源
      最近更新 更多