Thread join() 方法将无法等待线程在 Windows Phone 8 中完成

Thread's join() method won't work for waiting the thead to finish in Windows Phone 8

我正在为 WP8 进行 SharpBox 身份验证。我搜索了 "wait for a thread to finish",得到了很多建议使用 join() 的答案。所以我将它添加到点击处理程序中的代码中:

 private async void uploadBtn_Tap(object sender, System.Windows.Input.GestureEventArgs e)
 {
     System.Threading.Thread thread = new System.Threading.Thread(getMyToken);
     thread.Start(); // Start a new non-UI thread to handle the request
     thread.Join();

     // The following codes must wait for the result of getMyToken!!!

     // the rest of the authenticating codes here
 }

非UI线程的getMyToken方法(以下所有变量都在构造函数之前声明,因此可以在其他方法中重复使用):

 public async void getMyToken()
 {
      Debug.WriteLine("GOT IN!");
      config = CloudStorage.GetCloudConfigurationEasy(nSupportedCloudConfigurations.DropBox) as DropBoxConfiguration;
      Debug.WriteLine("Done 1st");

      requestToken = DropBoxStorageProviderTools.GetDropBoxRequestToken(config, "MY KEY", "MY SECRET");
      Debug.WriteLine("Done 2nd);

      AuthorizationUrl = DropBoxStorageProviderTools.GetDropBoxAuthorizationUrl(config, requestToken);
      Debug.WriteLine("Done 3rd");

      Uri requestUri = new Uri(AuthorizationUrl);
      Debug.WriteLine("Done 4th");

      Uri redirectUri = new Uri("http://localhost");
      Debug.WriteLine("Done 5th");
}

thread.Join(); 下面的代码只是挂起,调试器只到达 GOT IN。如果我删除 thread.join();,下面的代码 thread.Join(); 会抛出 NullReferenceException 因为非 UI 线程还没有完成它的工作..

但是如果我删除thread.join();下面的所有代码和thread.join();本身,调试器可以到达Done 5th

我不知道我做错了什么。谢谢。

getMyToken 中删除 async 关键字,然后从您的 Tap 处理程序中这样调用它:

await Task.Run(() => getMyToken());

这将 运行 后台线程上的 DropBox 代码(大概 DropBox API 正在进行网络调用并且可能需要很长时间)但保持 UI 响应直到API returns.