[英]C# return value from async function
I'm trying to write a C# async function which could return a value.我正在尝试编写一个可以返回值的 C# 异步函数。
Current function code:当前功能代码:
public async void getTwitterFollowerCount()
{
var twitterCtx = new TwitterContext(SharedState.Authorizer);
var followers = await (from follower in twitterCtx.Friendship where follower.Type == FriendshipType.FollowerIDs && follower.UserID == "15411837" select follower).SingleOrDefaultAsync();
if (followers != null && followers.IDInfo != null && followers.IDInfo.IDs != null)
{
followers.IDInfo.IDs.Count();
}
}
I've been trying something similare to this:我一直在尝试类似的东西:
public async int getTwitterFollowerCount()
{
var twitterCtx = new TwitterContext(SharedState.Authorizer);
var followers = await (from follower in twitterCtx.Friendship where follower.Type == FriendshipType.FollowerIDs && follower.UserID == "15411837" select follower).SingleOrDefaultAsync();
if (followers != null && followers.IDInfo != null && followers.IDInfo.IDs != null)
{
return followers.IDInfo.IDs.Count();
}
}
But never got it working.但从来没有让它工作。 Does someone have a idea, how I could be able to return a value from this async function?
有人有想法,我怎么能从这个异步函数返回一个值?
Would appreciate any kind of help.将不胜感激任何形式的帮助。
Change return type of getTwitterFollowerCount
to Task<int>
.将
getTwitterFollowerCount
返回类型更改为Task<int>
。 Read more at MSDN https://msdn.microsoft.com/en-us/library/mt674882.aspx .在 MSDN https://msdn.microsoft.com/en-us/library/mt674882.aspx阅读更多信息。
As others have indicated,正如其他人指出的那样,
Task<int>
is the correct return type.是正确的返回类型。
Also, never have an 'async void' method if you can avoid it since it's impossible to await a method that returns void.此外,如果可以避免使用“async void”方法,则永远不要使用它,因为不可能等待返回 void 的方法。 The only case where you should do this is with event handlers.
您应该这样做的唯一情况是使用事件处理程序。 Otherwise, always return 'Task'.
否则,始终返回“任务”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.