I want to get a Task<T>
which is returned by a property.
enum ProgressStatus
{
Success = 0,
Failure
}
interface IMessage
{
Task<ProgressStatus> AddMessage();
}
class Message : IMessage
{
public Task<ProgressStatus> Add
{
get
{
return AddMessage();
}
set
{
Add = value;
}
}
public async Task<ProgressStatus> AddMessage()
{
using (var db = new VinaChanelDbContext())
{
try
{
//do stuff...
await db.SaveChangesAsync();
return ProgressStatus.Success;
}
catch { return ProgressStatus.Failure; }
}
}
}
My question is: How to switch
property new Message().Add
?
var msg = new Message();
switch (msg.Add) //this must be an enum instead of Task<enum>
{
case ProgressStatus.Success:
return Json(new { success = true });
case ProgressStatuc.Failure:
default:
return Json(new { success = false });
}
Why must it be Task<T>
? Because I want to use async
and await
inside method AddMessage
.
Is it possible?
Why must it be
Task<T>
?
To follow the chain, Add
must be Task<ProgressStatus>
because it returns AddMessage();
, which is Task<ProgressStatus>
.
How to
switch
propertynew Message().Add
?
To answer is as simple as "don't". Instead, await
the Task<ProgressStatus>
and use the result. A Task hasn't necessarily been run yet: the await
indicates that the current code will wait for the task to be done.
ProgressStatus statusAfterAdding = await msg.Add;
switch (statusAfterAdding)
{
// ...
}
You already use await
with await db.SaveChangesAsync();
, and this is the same thing: SaveChangesAsync
returns a Task<int>
which you await
(although you ignore the returned int
).
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.