zoukankan      html  css  js  c++  java
  • 在多线程环境下使用HttpWebRequest或者调用Web Service

    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Net;

    namespace MultiThread
    {
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    class Class1
    {
    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    Thread thread = new Thread(new ThreadStart(MakeThread));
    thread.Start();
    Console.ReadLine();
    }

    private static int count = 30;
    private static int max = 10;
    private static int x = 0;
    private static int y = 0;

    private static void MakeThread()
    {
    while (x < count)
    {
    if (y < max)
    {
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create ("http://www.google.com");
    req.Timeout = 100000;
    ThreadPool.QueueUserWorkItem(new WaitCallback(MakeWebRequest), req);
    Interlocked.Increment(ref y);
    }
    Thread.Sleep(0);
    }
    Console.WriteLine("=======================================");
    }

    private static void MakeWebRequest (object obj)
    {
    HttpWebRequest req = obj as HttpWebRequest;
    HttpWebResponse res = null;
    try
    {
    Console.WriteLine ("\nConnecting to " + req.RequestUri);
    res = (HttpWebResponse) req.GetResponse ();
    Console.WriteLine("[" + AppDomain.GetCurrentThreadId() + "] ContentLength:" + res.ContentLength);
    Console.WriteLine ("Connected.\n");
    }
    catch (Exception e)
    {
    if (res != null)
    {
    res.Close ();
    Interlocked.Increment(ref x);
    Interlocked.Decrement(ref y);
    res = null;
    }
    Console.WriteLine ("Source : " + e.Source);
    Console.WriteLine ("Message : " + e.Message);
    Console.WriteLine(e.ToString());
    Debug.WriteLine(e.ToString());
    }
    finally
    {
    if (res != null)
    {
    res.Close ();
    Interlocked.Increment(ref x);
    Interlocked.Decrement(ref y);
    }
    }
    }
    }
    }
  • 相关阅读:
    2021hdu多校第二场补题
    ORACLE数据库之SQL语言基础
    EXCEL应用
    element-ui闭坑
    题解 CF1559E 【Mocha and Stars】
    题解 CF1530D 【Secret Santa】
    题解 CF1209E2 【Rotate Columns (hard version)】
    题解 CF761E 【Dasha and Puzzle】
    题解 UVA437 【巴比伦塔 The Tower of Babylon】
    题解 P6100 【[USACO19FEB]Painting the Barn G】
  • 原文地址:https://www.cnblogs.com/kokoliu/p/475911.html
Copyright © 2011-2022 走看看