简体   繁体   中英

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?

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;
            }
    }
}

Your problem is that every character your user types into the textbox results in a WebClient download that has to complete before the next keypress can be accepted. I'd suggest you do the following...

Create a timer that starts or restarts each time the user enters a character and that when expires disables the textbox and runs the search before re-enabling the textbox. You'd also do well to use an asynchronous WebClient call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM