I have the following method:
private async Task<Request> UpdateRequest(string id, RequestOutcome outcome)
{
var request = Db.Request.Where(r => r.Id.ToString().Equals(id)).First();
request.DateLastRead = DateTime.Now;
request.DateConcluded = request.DateLastRead;
request.Outcome = (int) outcome;
Db.Entry(request).State = EntityState.Modified;
if (await Db.SaveChangesAsync() <= 0) return null;
return outcome == RequestOutcome.Accept ? request : null;
}
This is called by the following:
public ActionResult Accept(string id)
{
var request = UpdateRequest(id, RequestOutcome.Accept);
if (request.Result != null)
{
var c = request.DateConcluded;
}
}
How do I check if the update was successful outside of the method? Should I say request != null
? When I do, I constantly get a warning that expression is always true.
How do I access request.DateConcluded property because it was made into a task.
You want to return a task result to the client. Set the task's Result property with your user defined result object. The task's Result property is serialized and returned back to the client.
The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.
Async methods can have the following return types: Task, for an async method that performs an operation but returns no value. Task<TResult>, for an async method that returns a value. void , for an event handler.
What Is A Task In C#? A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the . NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.
You are running asynchronous code synchronously.
You must use await
before your method to run your method asynchronously - this will handle getting the result of the task for you.
If you run the code synchronously you must then get the result of the task.
For Async:
public async Task<ActionResult> Accept(string id)
{
var request = await UpdateRequest(id, RequestOutcome.Accept);
if (request!= null)
{
var c = request.DateConcluded;
}
}
For Sync
public ActionResult Accept(string id)
{
var request = UpdateRequest(id, RequestOutcome.Accept).Result;
if (request != null)
{
var c = request.DateConcluded;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With