WebClient UploadValues 连接意外关闭

WebClient UploadValues connection closed out unexpectedly

我在尝试将 post 数据发送到我的 php 服务器时遇到错误。 此调用在我的程序中的一个位置有效,但在第二个位置无效。

我的 php 代码只是一个简单的回显,我已经测试了页面并且运行良好。

Exception thrown: 'System.Net.WebException' in System.dll The underlying connection was closed: The connection was closed unexpectedly.

public static class NetworkDeploy 
{
    public delegate void CallBack(string response);

    public static void SendPacket(string url, CallBack callback) 
    {
        SynchronizationContext callersCtx = SynchronizationContext.Current;
        Thread thread = new Thread(() =>
        {
            using (var client = new WebClient())
            {
                NameValueCollection values = new NameValueCollection();
                values["test"] = "test";
                // exception occurs at the next line
                byte[] uploadResponse = client.UploadValues(url, "POST", values);
                string response = Encoding.UTF8.GetString(uploadResponse);
                if (callback != null) callersCtx.Post(new SendOrPostCallback((_) => callback.Invoke(response)), null);
            }
        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
    }
}

我试过将异常行放在这样的 for 循环中:

byte[] uploadResponse = null;
for (int i=0; i<10; i++)
{
    try
    {
        // exception occurs at the next line
        uploadResponse = client.UploadValues(url, "POST", values);
        break;
    } catch (Exception e) { }
}

而 php 代码只是

<?php
echo "Success";

我怀疑问题出在 SynchronizationContext.Current 的使用以及如何调用委托以回调主 UI 线程。

我已经编写了一个示例概念证明来使用任务工厂和匿名委托来执行此操作,它应该允许您从 UI 线程调用任务,然后在 [=18] 上处理完成的结果=]线程。

我希望这能解决问题:

    Task<string> SendPacket(string url)
    {
        return Task<string>.Factory.StartNew(() =>
        {
            using (var client = new WebClient())
            {
                NameValueCollection values = new NameValueCollection();
                values["test"] = "test";
                // exception occurs at the next line
                byte[] uploadResponse = client.UploadValues(url, "POST", values);
                return Encoding.UTF8.GetString(uploadResponse);
            }
        });
    }

    void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            SendPacket("http://localhost:8733/api/values").ContinueWith(task => DoSomethingOnCallback(task.Result));
        }
    }

    void DoSomethingOnCallback(string response)
    {
        Console.WriteLine(response);
    }