简体   繁体   中英

Task.Run does't run the task in background c#

I need to call a function inside the task without hanging the UI, this is what I do but faced hanging with the main thread which is the login form, so what is missing or if I implement by wrong way?

private async void BtnLogin_Click(object sender, EventArgs e)
{
     await LoginAsync();
}

private async Task<bool> LoginAsync()
{
     LoginResponse loginResponse = await Task.Run(() =>
                    loginService.Login(new LoginModel { UserName = txtUN.Text, Password = txtPW.Text })
     );

     return loginResponse.Success;
}

Backend code:

public interface ILoginService
{
     Task<LoginResponse> Login(LoginModel model);
     Task<LogoutResponse> Logout();
}

public partial class LoginService : ILoginService
{
    public Task<LoginResponse> Login(LoginModel model)
    {
         return LoginAsync(model);
    }

    private async Task<LoginResponse> LoginAsync(LoginModel model)
    {
        for (int i = 0; i < 100000; i++)
        {
            Console.WriteLine(i);
        }

        string _Url = BaseUrl + "/login";
        try
        {
            model.CompanyName = System.Configuration.ConfigurationManager.AppSettings["Company_Name"];
            string Body = JsonConvert.SerializeObject(model);
            _logger.Info($"Login Request, Body: {Body}");
            HttpResponseMessage responseMessage = await client.PostAsync(new Uri(_Url), new 
            StringContent(Body, Encoding.UTF8, "application/json"));

            return JsonConvert.DeserializeObject<LoginResponse>(await 
            responseMessage.Content.ReadAsStringAsync());
         }
         catch (Exception e)
         {
            HandleException(e);
            return new LoginResponse
            {
               HttpStatus = HttpStatusCode.InternalServerError,
               Message = "Internal server error"
            };
         }
    }
}

so anyone please can guide me to solve this issue.

Console.WriteLine(i);

is the only thing that is highly suspicious in your code. This is a bit stating the obvious but when you use Task.Run , the passed-in action is going to be scheduled to the default task scheduler, the default ThreadPool if you hadn't defined any, and then a thread in the threadpool will pick up the work while your main UI thread is freely waiting for another UI actions. So there shouldn't be freezing on your UI application because of the fact above .

If it looks like freezing, you probably run the app through your Visual Studio with F5 ( if F5 means Start Debugging in your hot-key configuration ). Becuase Console.WriteLine will be vomitting all the index values on the "Output" window somewhere in the IDE, and make your action against the app unresponsive, even though your UI in the app is not actually freezing.

Try running your app outside of your IDE, simply CTRL + F5 ( Start without debugging ) if you still want to run the app via Visual Studio or just execute the .exe directly. Then I guess you can see your UI working fine.

This is because the button click event handler is awaiting the task (ie it is waiting for the task to complete). You also don't do anything with the result of the task.

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