C#client.GetStringAsync(url)stuck

问题描述:

我不明白我的代码有什么问题。我正在使用https://github.com/elcattivo/CloudFlareUtilities解决云耀斑js。我想从页面的数据,我使用此代码:C#client.GetStringAsync(url)stuck

public Form1() 
{ 
    InitializeComponent(); 
    Test1("https://SiteWithCloudFlareProtection.com/"); 
    Thread.Sleep(60000); 
} 

async void Test1(string url) 
{ 
    HttpClient HttpClientWithoutCloudFlare = new HttpClient(new ClearanceHandler()); 
    string json = await HttpClientWithoutCloudFlare.GetStringAsync(url).ConfigureAwait(false); 
    MessageBox.Show("Done"); 
} 

void Test2(string url) 
{ 
    HttpClient HttpClientWithoutCloudFlare = new HttpClient(new ClearanceHandler()); 
    string json = HttpClientWithoutCloudFlare.GetStringAsync(url).Result; 
    MessageBox.Show("Done"); 
} 

没有Thread.Sleep(60000)Test1完美的作品。随着Thread.Sleep(60000)Test1斯托克斯,Test2总是在命令GetStringAsync(url) stucks。 Test1(url).Wait();也有问题。

我错过了什么吗?

我只需要解决云耀斑保护和从页面获取数据。我需要同步做到这一点。

+0

将'Test2'修改为'async'。它会在您立即使用'Result'时同步运行。 – Venky

+0

@Venky我需要同步做到这一点。 –

+0

你没有使用'await'。因此即使使用'async'关键字,您的代码也可以同步运行。 – Venky

您不应该在构造函数中调用async方法。你不应该阻止异步代码。这可能导致死锁。你可以阅读更多关于此这里:http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

由于Test1async方法应该返回一个Task而不是无效:

async Task Test1(string url) 
{ 
    HttpClient HttpClientWithoutCloudFlare = new HttpClient(new ClearanceHandler()); 
    string json = await HttpClientWithoutCloudFlare.GetStringAsync(url); 
    MessageBox.Show("Done"); 
} 

然后,您可以await它一旦Form已由例如搬运装该Shown事件Form的:

public Form1() 
{ 
    InitializeComponent(); 

    Shown += async (s, e) => 
    { 
     await Test1("https://SiteWithCloudFlareProtection.com/"); 
     //Thread.Sleep(60000); 
    }; 
} 

请参考以下ARTI有关C#中的异步编程的最佳实践的更多信息,请参阅:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx