c# - 如何更改任务中的值

标签 c# .net asynchronous asp.net-web-api async-await

我有一个 async 函数。有多个级别的函数调用都返回一个 Task。在此链中的某个点,我必须修改结果的值。我想在不中断 async 函数流程的情况下执行此操作。观察:

[HttpGet]
[Route("GetWeb")]
public async Task<IHttpActionResult> GetResult([FromUri] string url)
{
    var result = await GetPageText(url);
    return Ok(result);
}

private Task<string> GetPageText(string url)
{
    Task<string> data = GetDataAsync(url);
    //here I would like to manipulate the data variable
    return data;
}

在函数 GetPageText 中,我如何在不中断异步流的情况下操作数据变量。这可能吗?

最佳答案

您无法更改任务的值(value),您需要创建一个新的。 async 的方法是等待原始结果并将该方法标记为 async(只有当您需要原始任务的结果时才会出现这种情况):

private async Task<string> GetPageText(string url)
{
    var result = await GetDataAsync(url);
    return result + "bar";
}

关于c# - 如何更改任务中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27707935/

相关文章:

c# - 随机数 0's or 1' s

javascript - 如何检查NodeJS程序是否即将存在

asynchronous - 如何提高Kafka Producer在同步模式下的性能

c# - 为什么 JsonConvert 不反序列化这个对象?

c# - C#中奇怪的 float 运算操作

c# - 如何使用 JSON.NET 遍历嵌套字典?

.net - 用于验证十六进制字符串的正则表达式

asp.net - 在异步 WebMethod 调用后更新 UI

C#如何比较两个字符串并指出哪些部分不同

c# - 如果适用,将嵌套的 ForEach 替换为 Select