С точки зрения исчерпания сокетов и потокобезопасности? Оба повторно используют экземпляр HttpClient, верно?
Я не могу сейчас реализовать IHttpClientFactory. Нам сложно реализовать внедрение зависимостей.
Первый фрагмент кода:
Код: Выделить всё
class Program
{
private static HttpClient httpClient;
static void Main(string[] args)
{
httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("your base url");
// add any default headers here also
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minute timeout
MainAsync().Wait();
}
static async Task MainAsync()
{
await new MyClass(httpClient).StartAsync();
}
}
public class MyClass
{
private Dictionary myDictionary;
private readonly HttpClient httpClient;
public MyClass(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task StartAsync()
{
myDictionary = await UploadAsync("some file path");
}
public async Task UploadAsync(string filePath)
{
byte[] fileContents;
using (FileStream stream = File.Open(filePath, FileMode.Open))
{
fileContents = new byte[stream.Length];
await stream.ReadAsync(fileContents, 0, (int)stream.Length);
}
HttpRequestMessage requestMessage = new HttpRequestMessage();
// your request stuff here
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
// parse response and return the dictionary
}
}
Код: Выделить всё
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
}
static async Task MainAsync()
{
await new MyClass().StartAsync();
}
}
public class MyClass
{
private Dictionary myDictionary;
private static readonly HttpClient httpClient= = new HttpClient() { BaseAddress = new Uri("your base url"), Timeout = new TimeSpan(0, 2, 0) };
public async Task StartAsync()
{
myDictionary = await UploadAsync("some file path");
}
public async Task UploadAsync(string filePath)
{
byte[] fileContents;
using (FileStream stream = File.Open(filePath, FileMode.Open))
{
fileContents = new byte[stream.Length];
await stream.ReadAsync(fileContents, 0, (int)stream.Length);
}
HttpRequestMessage requestMessage = new HttpRequestMessage();
// your request stuff here
HttpResponseMessage httpResponse = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
// parse response and return the dictionary
}
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... mework-4-7
Мобильная версия