如何运行返回不同类型的并行方法?



我正在创建与商店API通信的应用程序。我已经写了大约30个代表API请求的类,我想知道如何并行运行这些请求。

我已经尝试完成任务的List,但它不工作,因为函数的不精确返回类型。

例如这些是请求类:

public class GetOrderStatusList : IRequest<GetOrderStatusList.Response> {
public class Status {
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
}
public class Response : Output {
[JsonPropertyName("statuses")]
public List<Status> Statuses { get; set; }
}
}
public class GetProductsPrices : IRequest<GetProductsPrices.Response> {
[JsonPropertyName("storage_id")]
public string StorageId { get; set; }
public class Product {
public class Variant {
[JsonPropertyName("variant_id")]
public int VariantId { get; set; }
[JsonPropertyName("price")]
public decimal Price { get; set; }
}
[JsonPropertyName("product_id")]
public int ProductId { get; set; }
[JsonPropertyName("price")]
public decimal Price { get; set; }
[JsonPropertyName("variants")]
public List<Variant> Variants { get; set; }
}
public class Response : Output {
[JsonPropertyName("storage_id")]
public string StorageId { get; set; }
[JsonPropertyName("products")]
public List<Product> Products { get; set; }
}
}

输出、IRequest和向服务器发送请求的方法:

public interface IRequest<TResponse> { }
public class Output {
[JsonPropertyName("status")]
public string Status { get; set; }
[JsonPropertyName("error_message")]
public string? ErrorMessage { get; set; }
[JsonPropertyName("error_code")]
public string? ErrorCode { get; set; }
}
public async Task<TResponse> SendRequestAsync<TResponse>(IRequest<TResponse> userRequest) where TResponse : Output {
var client = new RestClient(_url);
var method = GetRequestMethodName(userRequest);
var request = CreateRequest(method, userRequest);
var response = await ExecuteRequestAsync(client, request);
var serializedResponse = JsonSerializer.Deserialize<TResponse>(response.Content);
if( serializedResponse.Status == "ERROR") {
throw new BaselinkerException(serializedResponse.ErrorMessage, serializedResponse.ErrorCode); 
}
return serializedResponse;
} 

你的列表类型没有意义;它试图保存输出请求项,但该方法只返回输出,而不是输出请求。

您的收集类型应该是List<Task<Output>>,或者可能只是List<Task>

要在一个循环中运行多个不同的任务,没有一种既好又简单的方法。请注意,这不是async/task特有的问题:在一个循环中运行多个返回不同类型的非异步方法也没有好的和简单的方法。

下面是运行两个任务而不等待其中一个任务完成后再开始下一个任务的示例:

using System.Diagnostics;
var sw = Stopwatch.StartNew();
var t1 = F1();
var t2 = F2();

var n = await t1;
var s = await t2;
Console.WriteLine($"Elapsed {sw.ElapsedMilliseconds}");
async Task<int> F1()
{
await Task.Delay(TimeSpan.FromMilliseconds(100));
return 7;
}
async Task<string> F2()
{
await Task.Delay(TimeSpan.FromMilliseconds(200));
return "waves";
}

运行时间将是~200ms(也就是最慢的任务运行的时间),而不是300ms(也就是两个任务运行的时间总和)。

最新更新