如何制作多线程Web请求?

时间:2018-02-14 02:40:42

标签: c# multithreading

我已制作此代码,因此我可以查看有关我网站上用户的信息。下面的代码块有效,但是我在制作它时遇到了麻烦,所以我可以通过多线程更快地完成它。

static void Main(string[] args)
{
    Check();
    Console.ReadLine();
}

public static void Check()
{
    string Users = @"D:\stuff\1.1\Info.txt";
    foreach (string line in File.ReadLines(Users))
    {
        string[] Info = line.Split(':');
        string user = Combos[0];
        string pty = Combos[1];
        string PI = "";
        try
        {
            byte[] byteArray = Encoding.UTF8.GetBytes("{\"username\":\"" + user + "\",\"PTY\":\"" + pty + "\"}");
            CookieContainer cookieContainer = new CookieContainer();
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://LocalServer"); // my local server
            Request.CookieContainer = cookieContainer;
            Request.Method = "POST";
            Request.CookieContainer.Add(new Uri("https://LocalServer"), new Cookie("LANGUAGE", "en"));
            Request.CookieContainer.Add(new Uri("https://LocalServer"), new Cookie("DEFLANG", "en"));
            Request.ContentLength = byteArray.Length;
            Request.ContentType = "application/json;charset=UTF-8";
            Stream dataStream = Request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
            HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
            string Response = (new StreamReader(response.GetResponseStream())).ReadToEnd();
            PI = response.Cookies["PI"].ToString().Replace("PI=", "");
            Match Token = (new Regex("{\"access_token\":\"([^\"]*)")).Match(Response);
            string Token1 = Token.Groups[1].ToString();
            HttpWebRequest RCapture = (HttpWebRequest)WebRequest.Create("https://LocalServer/profiles" + PI + "/summary");
            RCapture.Method = "Get";
            RCapture.CookieContainer = cookieContainer;
            RCapture.Headers.Add("Authorization", "bearer " + Token1);
            HttpWebResponse RCap = (HttpWebResponse)RCapture.GetResponse();
            string CapR = (new StreamReader(RCap.GetResponseStream())).ReadToEnd();
            Match RInfo = (new Regex("(.*)")).Match(CapR);
            string ptyInfo = RInfo.Groups[1].ToString();
            float ptyInt = 0;
            Single.TryParse(ptyInfo, out ptyInt);
            if (ptyInt >= 10)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(user + ":" + pty + "   " + ptyInt);
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.WriteLine(user + ":" + pty + "   " + ptyInt);
            }
        }
        catch (WebException)
        {
        }
    }
}

我考虑过使用await命令进行异步操作,但我不确定这是否是最佳选择,或者我应该怎么做。

0 个答案:

没有答案