我正在为WP8进行SharpBox身份验证。我搜索“等待线程完成”,我得到了很多答案建议使用join()
。所以我将它添加到我在Click处理程序中的代码中:
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
。
我不知道我做错了什么。谢谢。
答案 0 :(得分:0)
从async
中移除getMyToken
关键字,然后从Tap
处理程序中调用它:
await Task.Run(() => getMyToken());
这将在后台线程上运行DropBox代码(可能是DropBox API正在进行网络调用并且可能需要很长时间)但是在UI返回之前保持UI响应。