Search code examples
c#.netwinformswebclientdownloadstring

WebClient DownloadString with TextChanged Event C#


I have an trouble in C# program which using php scripts to translate words and download the result string into TextBox.

My program has two TextBoxes

txtWord, txtTranslatedWord

and that's the simplified code

WebClient c = new WebClient();
private void txtWord_TextChanged(object sender, EventArgs e)
{
    string response = c.DownloadString("http://example.com/Services/Translator/lang/EnglishToArabic.php?Word=" + txtWord.Text);
    switch (response.ToLower())
    {
        case "not exist":
            {
                txtTranslatedWord.Text = "{Sorry but no translation for this word!}";
                break;
            }
        default:
            {
                txtTranslatedWord.Text = response;
                break;
            }
    }
}

The problem its when the text is changed the program lagging and looks like it would Stopped Working.

The program worked successfully but after so much lagging , especially if the writer is writing so fast.

I tried BackgroundWorker and make an delay like when user stop writing for 2 second then program start to translate but still lagging without any luck.

Is there any easy way to do this without problems?


Solution

  • Try to use asynchrony.

    WebClient does not support concurrent I/O operations, so will be use HttpClient.

    HttpClient client = new HttpClient();
    
    private async void txtWord_TextChanged(object sender, EventArgs e)
    {
        var response = await client.GetStringAsync(
            "http://example.com/Services/Translator/lang/EnglishToArabic.php?Word=" + txtWord.Text);
        switch (response.ToLower())
        {
            case "not exist":
                {
                    txtTranslatedWord.Text = "{Sorry but no translation for this word!}";
                    break;
                }
            default:
                {
                    txtTranslatedWord.Text = response;
                    break;
                }
        }
    }