简体   繁体   中英

Object reference not set to an instance of an object when calling asynchronous method

Twitter does not provide user Birthdays through its REST API. Because of that, I prepared a nullable DateTime property.

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:

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.

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.

An alternative could be to just use the Task.FromResult<DateTime?>(null)

as.

public Task<DateTime?> GetUserBirthDayAsync()
{
    return Task.FromResult<DateTime?>(null);
}

MSDN Documentation

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. 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() . And you use it when you try to await this task.

So the NullReferenceException is raised by the await (or the code the compiler creates for it).

So what you probably want to do is to return a Task<DateTime?> that returns a null as result type:

public Task<DateTime?> GetUserBirthDayAsync(){
    return Task.Run(() => (DateTime?)null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM