【发布时间】:2016-01-13 07:28:34
【问题描述】:
所以在涉足 Java 和 HttpClient 之后,我决定过渡到 C# 以尝试在提高速度的同时降低内存使用量。我一直在阅读这里的成员提供的大量关于异步与多线程的文章。看来多线程将是更好的方向。
我的程序将访问服务器并一遍又一遍地发送相同的请求,直到检索到 200 代码。原因是因为在高峰时段交通非常繁忙。它使服务器很难到达并引发 5xx 错误。代码非常简单,我还不想添加循环以帮助查看者简化。
我觉得我正朝着正确的方向前进,但我想与社区联系以改掉任何不良习惯。再次感谢您的阅读。
版主注意:我要求检查我的代码是否存在差异,我很清楚多线程 HttpClient 是可以的。
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Threading;
namespace MF
{
class MainClass
{
public static HttpClient client = new HttpClient();
static string url = "http://www.website.com";
public static void getSession() {
StringContent queryString = new StringContent("{json:here}");
// Send a request asynchronously continue when complete
var result = client.PostAsync(new Uri(url), queryString).Result;
// Check for success or throw exception
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
}
public static void Run()
{
getSession ();
// Not yet implemented yet..
//doMore ();
}
public static void Main (string[] args)
{
Console.WriteLine ("Welcome!");
// Create the threads
ThreadStart threadref1 = new ThreadStart(Run);
ThreadStart threadref2 = new ThreadStart(Run);
Console.WriteLine("In the main: Creating the threads...");
Thread Thread1 = new Thread(threadref1);
Thread Thread2 = new Thread(threadref1);
// Start the thread
Thread1.Start();
Thread2.Start();
}
}
}
另外,我不确定这是否重要,但我正在我的 MacBook Pro 上运行它,并计划在我的 BeagleBoard 上运行它。
【问题讨论】:
-
getSession绝对应该是@987654324@。调用异步方法,例如PostAsync,并等待结果,是不可行的;不要在线程之间共享HttpClient;不要手动创建单独的线程,只需调用async方法N次创建N个任务。 -
文档声明它不是线程安全的。您可以为每个请求创建
HttpClient的新实例。如果您更喜欢异步而不是多线程,我希望您的应用程序能够很好地扩展。而不是使用 Result 属性,等待任务。 -
真的吗?我读了另一个文档,说它是 Thread 安全的,我一定读过一篇不可信的文章。
-
我用小待办事项列表更新了答案,如果你也想要答案中的伪代码,请告诉我
标签: c# multithreading httpclient