繁体   English   中英

C#许多异步HttpWebRequest

[英]c# many async HttpWebRequest

我尝试使许多异步HttpWebRequest 这是我的测试代码:

class Program
{
    static void Main(string[] args)
    {
        Test();
        Console.ReadLine();
    }

    public static async void Test()
    {
        for (int i = 0; i < 10; i++)
        {
            int val = i;
            await Task.Run(() => WR(val));
        }
    }

    static async void WR(int msg)
    {
        Console.WriteLine(msg + " begin");

        string url = "https://stackoverflow.com";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>
                (request.BeginGetResponse, request.EndGetResponse, null);

        Console.WriteLine(msg + " status code: " + response.StatusCode);
        Console.WriteLine(msg + " end");
    }
}

结果:

0 begin
1 begin
2 begin
3 begin
4 begin
5 begin
6 begin
7 begin
8 begin
9 begin
0 status code: OK
0 end
1 status code: OK
1 end

1 end什么也没发生。 输出大约30秒后,我可以看到:

The thread 0x6634 has exited with code 0 (0x0).
The thread 0x5620 has exited with code 0 (0x0).
The thread 0x4d08 has exited with code 0 (0x0).
The thread 0x39b8 has exited with code 0 (0x0).
The thread 0x3454 has exited with code 0 (0x0).
The thread 0x99c has exited with code 0 (0x0).
The thread 0x6be0 has exited with code 0 (0x0).

但是也没有例外,并且控制台没有关闭。

我的错误在哪里?

回答:

不记得response.Dispose();

我已经运行了您的代码并获得如下输出:

0 begin
1 begin
2 begin
3 begin
4 begin
5 begin
6 begin
7 begin
8 begin
9 begin
0 status code: OK
0 end
5 status code: OK
5 end
8 status code: OK
8 end
4 status code: OK
4 end
3 status code: OK
3 end
2 status code: OK
2 end
6 status code: OK
6 end
1 status code: OK
1 end
7 status code: OK
7 end
9 status code: OK
9 end

当您按Enter键时,由于Console.ReadLine();应用程序将关闭Console.ReadLine(); 在您的主要方法中。 它等待程序,直到从控制台获得输入。

不记得response.Dispose();

static async void WR(int msg)
{
    Console.WriteLine(msg + " begin");

    string url = "https://stackoverflow.com";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    var response = (HttpWebResponse)await Task.Factory.FromAsync<WebResponse>
            (request.BeginGetResponse, request.EndGetResponse, null);

    Console.WriteLine(msg + " status code: " + response.StatusCode);
    Console.WriteLine(msg + " end");
    response.Dispose();
}

我将其设置为自己的静态方法,该方法将返回字符串,以便您了解发生了什么。 而且我不会依赖任何类型的xml文件,除非它是从API调用返回的XML。 我在这里发布,但如果需要,您可以获取。 不知道您的设置在后端如何。 核实:

public static string PostXMLDataCS()
    {
        bool debugging = false;
        try
        {

            string iConnectAuth = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
  "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" +
            "<soapenv:Header/>" +
       "<soapenv:Body>" +
        "<tem:Authenticate>" +
         "<!--Optional:-->" +
          "<tem:TenantID>TenantID</tem:TenantID>" +
               "<!--Optional:-->" +
                "<tem:Username>Username</tem:Username>" +
                     "<!--Optional:-->" +
                      "<tem:Password>password</tem:Password>" +
                           "</tem:Authenticate>" +
                            "</soapenv:Body>" +
                             "</soapenv:Envelope>";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.example.com/services/ByDesign/Inventory.svc");
            byte[] bytes;
            bytes = System.Text.Encoding.ASCII.GetBytes(iConnectAuth);

            request.ContentType = "text/xml; charset=utf-8";
            request.Accept = "gzip,deflate";
            request.ContentLength = bytes.Length;
            request.Method = "POST";
            request.Headers.Add("SOAPAction", "http://tempuri.org/IInventory/Authenticate");
            request.KeepAlive = true;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
            HttpWebResponse response;
            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                string responseStr = new StreamReader(responseStream).ReadToEnd();
                response.Close();
                //MessageBox.Show(responseStr);
                return responseStr;
            }
        }
        catch (Exception e)
        {
            if (debugging == true)
            {
                MessageBox.Show("There was a problem authenticating for the check inventory with iConnect. Error: " + e);
            }

            string messageSubject = "There was a problem authenticating for the check inventory with iConnect.";
            string messageBody = "There was a problem authenticating for the check inventory with iConnect. Error: ";
            string kiboSendEmail = string.Empty;
            SendEmail sendEmail = new SendEmail();
            return kiboSendEmail = sendEmail.SendEmailCS(messageSubject, messageBody, e);

        }
        return null;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM