AussieJoe
AussieJoe

Reputation: 1370

How to check an underlying async Task.Result result for null

Background

Currently I have a .NET Core 3.1 WebAPI method that is communicating with a SOAP service asynchronously. When I run my task and get a response it usually works, but sometimes the SOAP service will send an 200 Ok() with an empty response. This is wreaking havoc for me. How can I check that the underlying Result/GetSomeFancyDataResult is null?

Because GetSomeFancyDataResult is a result under the "Result", I am getting a valid "Result" but "GetSomeFancyDataResult" is null and when I try to check it for null, I get an error that it's not instantiated.

Example Code

    // make an async request to legacy SOAP service
    var client = new mySoapService.serviceClient();
    var request = new mySoapService.GetSomeFancyDataRequest(1, "abc", 234);
    var task = Task.Run(async () => await client.GetSomeFancyDataAsync(request));

    // how to check if GetSomeFancyDataResult exists ?
    if (task.Result.Equals(null) || task.Result.GetSomeFancyDataResult.Equals(null))
        return null; // exit here, abort!

    // process the results when data is found in the result ??
    var results = task.Result.GetSomeFancyData.Select(result => result.MyFancyFieldOne);

My Problem

My problem is that this doesn't work as expected...

// how to check if GetSomeFancyDataResult exists ?
if (task.Result.Equals(null) || task.Result.GetSomeFancyDataResult.Equals(null))
    return null; // exit here, abort!

Maybe I have stared at this for too long. What am I overlooking here? I have searched SO and the interwebs and haven't found how to check this for null correctly. Help?

Upvotes: 1

Views: 4266

Answers (2)

AussieJoe
AussieJoe

Reputation: 1370

Using @Matt Johnson-Pint's suggestion works cleanest for me.

// make an async request to legacy SOAP service
var client = new mySoapService.serviceClient();
var request = new mySoapService.GetSomeFancyDataRequest(1, "abc", 234);
var task = Task.Run(async () => await client.GetSomeFancyDataAsync(request));

// process the results when data is found in the result ??
var results = task.Result?.GetSomeFancyData?.Select(result => result.MyFancyFieldOne);

if (results == null)
    return null;

return results;

Upvotes: 0

Nkosi
Nkosi

Reputation: 247413

Consider just awaiting the result and perform your check on the returned value.

// make an async request to legacy SOAP service
var client = new mySoapService.serviceClient();
var request = new mySoapService.GetSomeFancyDataRequest(1, "abc", 234);
var result = await client.GetSomeFancyDataAsync(request);

//check if GetSomeFancyDataResult exists
if (result == null || result.GetSomeFancyDataResult == null)
    return null; // exit here, abort!

// process the results when data is found in the result ??
var results = result.GetSomeFancyData.Select(x => x.MyFancyFieldOne);

Upvotes: 2

Related Questions