Async Await 关键字是解决您的情况的一种方法。但是,您的实际问题是您不了解GetAsync
呼叫的工作原理。当你说:
public static long CheckIfUserExist()
{
long UserID = -1;
client.GetAsync("me");
client.GetCompleted += (o, e) =>
{
// some code
if (Convert.ToInt64(eargs.Result) == 0)
{
UserID = Convert.ToInt64(eargs.Result);
}
return UserID;
}
}
它相当于:
public static long CheckIfUserExist()
{
long UserID = -1;
client.GetAsync("me");
client.GetCompleted += MyEventHandler;
}
void MyEventHandler(object sender, SomeEventArgs e)
{
// some code
if (Convert.ToInt64(eargs.Result) == 0)
{
UserID = Convert.ToInt64(eargs.Result);
}
return UserID; // <-- WHAT IS POINT OF RETURNING UserID FROM HERE??
// method maybe running on some other thread asynchronously to UI thread
}
您有两种可能性: 如果您的client
对象的GetCompleted
事件发生在 UI 线程上,您可以这样做:
client.GetCompleted += (o, e) =>
{
// some code
if (Convert.ToInt64(eargs.Result) == 0)
{
UserID = Convert.ToInt64(eargs.Result);
}
// your logic here
if (UserID == -1)
// WRONG RESULT <---
else
// RIGHT RESULT <---
}
如果GetCompleted
UI 线程上没有发生事件:
client.GetCompleted += (o, e) =>
{
// some code
if (Convert.ToInt64(eargs.Result) == 0)
{
UserID = Convert.ToInt64(eargs.Result);
}
// let UI thread know we've got the result
Dispatcher.Invoke( (Action)(() => { NotifyUIThread(UserID) } ));
}
...
void NotifyUIThread(long UserId) //This runs on UI thread
{
if (UserID == -1)
// WRONG RESULT <---
else
// RIGHT RESULT <---
}
另外,请注意在您致电之前订阅事件GetAsync
client.GetCompleted += (o, e) => { ... } //subscribe first
client.GetAsync("me"); // call GetAsync later
如果在 WP7 上 - 你可能会遇到问题Dispatcher.Invoke
:Can't use dispatcher on WP7