2016-07-26 102 views
-3

我在php中有以下代码运行完美,问题在于它的运行速度很慢,因为它在循环中运行多次。在php中实现多线程是另一个问题。但我知道如何在C#中执行多线程,因此如果任何人都可以将此函数转换为C#,我将处理多线程部分。curl等效于C#

function process_registration($reg,$phone,$key,$secret) 
    { 
    $fields['regno']= $reg; 
    $fields['phone']= $phone; 
    $fields['key']= $key; 
    $fields['secret']= $secret; 
    $process = curl_init('http://theip/registrationsearch/confirm_status.php'); 
    curl_setopt($process, CURLOPT_POSTFIELDS, $fields); 
    curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE); 
    $result = curl_exec($process); 
    $the_data=json_decode($result,true); 
    if($the_data['Status']==='Ok') return $the_data['registration_details']; 
    else return $the_data['Status']; 
    } 

我想在C#控制台应用程序中实现此功能。这样我就可以实现C#的多线程功能。 我试过用HttpClient没有成功,任何人都可以帮忙吗?

这是功能我在C#中没有,但我没有得到响应没有错误消息

static async Task<int> MainAsync(string[] args) 
    { 
     var client = new HttpClient(); 
     var keyValues = new List<KeyValuePair<string, string>>(); 
     keyValues.Add(new KeyValuePair<string, string>("key", args[0])); 
     keyValues.Add(new KeyValuePair<string, string>("secret", args[1])); 
     keyValues.Add(new KeyValuePair<string, string>("phone", args[2])); 
     keyValues.Add(new KeyValuePair<string, string>("regno", args[3])); 

     var requestContent = new FormUrlEncodedContent(keyValues); 

     HttpResponseMessage response = await client.PostAsync("http://theip/registrationsearch/confirm_status.php", requestContent); 
     HttpContent responseContent = response.Content; 
     Console.WriteLine("Waiting for response..."); 

     using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync())) 
     { 
      Console.WriteLine(await reader.ReadToEndAsync()); 
     } 
     return 1; 
    } 
+0

这将是最好展现你'C#'代码是什么错误,你得到,并且还可以改变你的问题。 – zulq

+0

我会建议尝试使用HttpClient而不是成功。你能证明你所尝试过的吗?也许那么我们可以指出你正确的方向。 – Jite

+0

你有没有试过寻找你在问什么? [这里](http://stackoverflow.com/q/21255725/1997232)是用“curl c#”(我不能判断它是否适用)。此外,你可以在标题中询问**好**(除非重复)具体问题,然后突然发布一堆代码并要求翻译它(这是**糟糕,没有人会这样做,你会得到低投票)。 – Sinatr

回答

1
private static async void TestAsyncPost() 
{ 
    var values = new Dictionary<string, string>(); 
    values.Add("regno", "testReg"); 
    values.Add("phone", "testPhone"); 
    values.Add("key", "testKey"); 
    values.Add("secret", "testSecret"); 
    var content = new FormUrlEncodedContent(values); 
    using (var client = new HttpClient()) 
    { 
    try 
    { 
     var httpResponseMessage = await client.PostAsync("http://theip/registrationsearch/confirm_status.php", content); 
     if (httpResponseMessage.StatusCode == HttpStatusCode.OK) 
     { 
     // Do something... 
     var response = await httpResponseMessage.Content.ReadAsStringAsync(); 
     Trace.Write(response); // response here... 
     } 
    } 
    catch (Exception ex) 
    { 
     Trace.Write(ex.ToString()); // error here... 
    } 
    } 
} 
+0

工作就像一个魅力!非常感谢! – indago