[英]Object reference not set to an instance of an object when calling asynchronous method
Twitter does not provide user Birthdays through its REST API. Twitter 不通过其 REST API 提供用户生日。 Because of that, I prepared a nullable DateTime property.因此,我准备了一个可为空的 DateTime 属性。
I also prepared an Interface for all social network services.我还为所有社交网络服务准备了一个接口。 Most of them are async Task methods.它们中的大多数是异步任务方法。
But I can't get to pass this error: Object reference not set to an instance of an object even though I'm not using the object.但我无法传递此错误:对象引用未设置为对象的实例,即使我没有使用该对象。
The Interface method GetUserBirthDayAsync is implemented as follow for Twitter service:接口方法 GetUserBirthDayAsync 针对 Twitter 服务实现如下:
public Task<DateTime?> GetUserBirthDayAsync(){
return null; // because twitter does not provide user birthday
}
and this is how I used the method:这就是我使用该方法的方式:
DateTime? BirthDate = await socialNetworkService.GetUserBirthDayAsync();
The error occurred in setting the value to the BirthDate variable.将值设置为 BirthDate 变量时发生错误。
What is happening?发生了什么? What is causing the exception?是什么导致异常?
Try this:试试这个:
public Task<DateTime?> GetUserBirthDayAsync()
{
return Task.Run(() => (DateTime?)null);
}
Or, better way to do the same:或者,更好的方法来做同样的事情:
public Task<DateTime?> GetUserBirthDayAsync()
{
return Task.FromResult<DateTime?>(null);
}
When you just return null
that means, your Task is null
, not result of async method.当您只返回null
,这意味着您的 Task 是null
,而不是异步方法的结果。
An alternative could be to just use the Task.FromResult<DateTime?>(null)
另一种方法可能是只使用Task.FromResult<DateTime?>(null)
as.作为。
public Task<DateTime?> GetUserBirthDayAsync()
{
return Task.FromResult<DateTime?>(null);
}
Creates a Task that's completed successfully with the specified result.创建一个以指定结果成功完成的任务。
Pretty much the same as the other options but IMHO it looks much cleaner.与其他选项几乎相同,但恕我直言,它看起来更干净。
You call await on null.您在 null 上调用 await。 I think you had something like this in mind:我想你有这样的想法:
public Task<DateTime?> GetUserBirthDayAsync(){
return Task.Run(() => (DateTime?)null); // because twitter does not provide user birthday like faceBK
}
even though am not using the object即使我没有使用该对象
Yes, you are using the object.是的,您正在使用该对象。 The object that is null
is the Task<DateTime?>
you return from GetUserBirthDayAsync()
.为null
的对象是您从GetUserBirthDayAsync()
返回的Task<DateTime?>
。 And you use it when you try to await
this task.当您尝试await
此任务时使用它。
So the NullReferenceException
is raised by the await
(or the code the compiler creates for it).因此NullReferenceException
由await
(或编译器为其创建的代码)引发。
So what you probably want to do is to return a Task<DateTime?>
that returns a null
as result type:所以你可能想要做的是返回一个Task<DateTime?>
,它返回一个null
作为结果类型:
public Task<DateTime?> GetUserBirthDayAsync(){
return Task.Run(() => (DateTime?)null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.