C# 从Windows服务运行时,WebClient请求速度非常慢
我正在尝试向WebAPI控制器发出HTTP POST请求,我正在从我的服务调用它。下面是我为进行调用而注入到业务层的类:C# 从Windows服务运行时,WebClient请求速度非常慢,c#,web-services,webclient,C#,Web Services,Webclient,我正在尝试向WebAPI控制器发出HTTP POST请求,我正在从我的服务调用它。下面是我为进行调用而注入到业务层的类: /// <summary> /// Makes calls to WebAPI /// </summary> public class WebApiProxy : IWebApiProxy { /// <summary> /// Sends HTTP POST requests to WebAPI along with po
/// <summary>
/// Makes calls to WebAPI
/// </summary>
public class WebApiProxy : IWebApiProxy
{
/// <summary>
/// Sends HTTP POST requests to WebAPI along with post values
/// </summary>
/// <param name="apiControllerName">The name of the controller to call</param>
/// <param name="postValues">The values to post to the controller</param>
public void SendApiRequest(string apiControllerName, NameValueCollection postValues)
{
using (var client = new WebClient())
{
try
{
//
// Breakpoint below this line, it's where it hangs
//
byte[] responsebytes = client.UploadValues(string.Format("http://localhost:8080/Api/{0}", apiControllerName), "POST", postValues);
string responsebody = Encoding.UTF8.GetString(responsebytes);
}
catch (Exception)
{
// TODO: Handle failed requests
}
}
}
}
我还创建了一个快速控制台应用程序来测试功能,这也可以在眨眼之间运行:
$.post("http://localhost:8080/Api/FinishedTakersCount", { "QuizOwnerUserId": 1, UrlId: "0mFjBH" }, null);
static void Main(string[] args)
{
while(true)
{
Console.WriteLine("Press Enter to make web request, or type exit...");
var typed = Console.ReadLine();
if (typed == "exit")
{
break;
}
using (var client = new WebClient())
{
try
{
var apiControllerName = "LiveTakersCount";
var postValues = new NameValueCollection();
postValues.Add("QuizOwnerUserId", "1");
postValues.Add("UrlId", "0mFjBH");
//TODO: Remove port from localhost
byte[] responsebytes = client.UploadValues(string.Format("http://localhost:8080/Api/{0}", apiControllerName), "POST", postValues);
string responsebody = Encoding.UTF8.GetString(responsebytes);
Console.WriteLine("HTTP Request completed.");
}
catch (Exception ex)
{
// TODO: Handle failed requests
Console.WriteLine("An Exception occurred with the web request: {0}", ex.Message);
}
}
}
}
您可以在上面的代码中看到我发布的值
我一辈子都无法理解为什么要花这么长时间,因为我正在窗口服务中运行请求
无论它是在本地计算机上安装时进行调用,还是在Visual Studio中进行调试-跳过客户端进行调试,都是一样的。上载值(…)大约需要30秒,结果很好
为什么它在我的Windows服务(在VS中安装或调试)中运行缓慢,但每次执行AJAX请求或控制台应用程序的请求时都会快速启动?在挂起期间暂停调试器。用外部代码发布调用堆栈。你认为这会揭示什么吗?在挂起之前,我在
客户端暂停它。上传值
并跨过它,看看需要多长时间。如果我不这么想,我不会问。堆栈告诉您程序现在正在做什么。函数名通常是描述性的。看起来将其更改为HttpClient()似乎已经达到了目的……我刚刚发现这并没有为我提供解决方案。一旦我开始等待该方法,它仍然挂起,这是不可接受的。这要花很长时间。奇怪的是,其他地方的服务都很好,而不是服务