异步等待关键字是解决你的情况的一种方式。但是,您的实际问题是您不了解GetAsync
调用的工作原理。 当你说:
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
}
有两种可能给你: 如果UI线程,你可以做到这一点上发生的client
对象的GetCompleted
事件:到
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;
}
}
它相当于
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
来源
2013-04-26 22:11:50
YK1
查找'async'和'等待' – 2013-04-26 06:27:11
你可以解释(简而言之)或gv我链接... – 2013-04-26 06:28:27
这里是[链接](https://www.google.com/search?q=webservice+async+await)和[另一个](http ://stackoverflow.com/search?q = [windows-phone-7] + async + webservice) – 2013-04-26 06:31:02