我尝试使用HttpClient
每5秒向云端发送一次数据。我并不真正关心响应(可能只记录错误)并且想要异步发送它以免阻塞我的主线程。我使用的是以下功能。当我尝试单独的输入时它工作正常,但是一旦我进入5秒循环就停止工作(不能向云发送任何东西)
private static async Task SendToCloudAsync(Dictionary<string, string> dict)
{
var client = new HttpClient();
client.BaseAddress = new Uri("some url");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
foreach (KeyValuePair<string, string> kvp in dict)
{
var path = string.Format("variabels/{0}/values.json", kvp.Key);
var request = new HttpRequestMessage(HttpMethod.Put, path);
request.Content = new StringContent(kvp.Value);
var response = await client.SendAsync(request);
}
}
然后在System.Timers.Timer
触发的函数中,我就这么称呼它
timer.Enabled = true;
timer.Interval = 50000;
timer.SynchronizingObject = this
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.someKindOfLoop);
private void someKindOfLoop(System.Timers.ElapsedEventArgs e)
{
var dict = generateDict();
var task = SendToCloudAsync(dict);
// I also tried Task.Run(async () => { await sendToCloud(dict); });
}
我做错了什么建议?