Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

c# - Correctly create a task for log-in function

I was working on my windows form program, and i saw that the login function (linked to a simple button) freeze my application. I searched on internet and i found how to create a task, but i'm not sure about how it works ...

That's my login function, how can i correctly translate it into a task?

string sURL = url + "/login";
string result = null;

await Task.Run(() =>
{
    try
    {
        result = Web_api.MakeRequest("POST", sURL); //return null if there is some error
    }
    catch(Exception ex)
    {
        Debug.WriteLine("[frmLogin] --> result: " + result);
    }
});

if(result != null)
{
    try
    {
        Login_response accepted = JsonConvert.DeserializeObject<Login_response>(result);
        Debug.WriteLine("[frm_Login] --> accepted: " + accepted);

        if (accepted.login)
        {
            //throw new Exception();  
            Debug.WriteLine("[frm_login]: result " + result);
            frmMain frm = new frmMain();                             //calling the new form
            frm.Show();                                              //new form is show-up
            this.Hide();                                             //log-in form hide
            frm.FormClosed += Frm_FormClosed;                        //close the form
        }
    }
    //if server is down, or the id or password is wrong 
    catch (Exception ex)
    {
        lblLoginError.Visible = true;                            //pop-up the error label
        pbLogin.Visible = false;                                 //hide the progress-bar
        this.Style = MetroFramework.MetroColorStyle.Red;         //changing the color of the form
        Debug.WriteLine("Exception: " + ex);
    }
}
else
{
    lblLoginError.Visible = true;                            //pop-up the error label
    pbLogin.Visible = false;                                 //hide the progress-bar
    this.Style = MetroFramework.MetroColorStyle.Red;         //changing the color of the form
}

EDIT: i provided a real (and working) soluction and i followed all the suggestion in the comments ... do you think this could be acceptable?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Execute any potentially long-running code on a background thread using a Task:

private async void btnLogin_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txtUser.Text.Trim()) || string.IsNullOrEmpty(txtPassword.Text.Trim()))
    {
        MessageBox.Show("You must insert a valid user/password format", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    //Progress bar start
    pbLogin.Visible = true; // BUT THIS PROGRESS BAR I STACK DUE TO STATIC DEFINITON OF LOGIN

    //Getting ID + Password
    User.username = txtUser.Text;
    User.password = txtPassword.Text;
    string sURL = Web_api.url + "/login";

    try
    {
        Login_response accepted = await Task.Run(() =>
        {
            //the following code gets executed on a background thread...
            string result = Web_api.MakeRequest("POST", sURL);
            Login_response accepted = JsonConvert.DeserializeObject<Login_response>(result);
            Debug.WriteLine("[frm_Login] --> accepted: " + accepted);
            return accepted;
        });
        
        //...and here you are back on the UI thread once the task has completed
        if (accepted.login)
        {
            //throw new Exception();  
            Debug.WriteLine("[frm_login]: result " + result);
            frmMain frm = new frmMain();                             //calling the new form
            frm.Show();                                              //new form is show-up
            this.Hide();                                             //log-in form hide
            frm.FormClosed += Frm_FormClosed;                        //close the form
        }
    }
    //if server is down, or the id or password is wrong 
    catch (Exception ex)
    {
        lblLoginError.Visible = true;                            //pop-up the error label
        pbLogin.Visible = false;                                 //hide the progress-bar
        this.Style = MetroFramework.MetroColorStyle.Red;         //changing the color of the form
        Debug.WriteLine("Exception: " + ex);
    }
}

Event handlers always return void. They are an exception to the rule that says that an async method always should return a Task or a Task<T>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...