简体   繁体   English

Task.Run 不在后台运行任务 c#

[英]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?我需要在任务中调用 function 而不挂起 UI,这就是我所做的,但面临挂起作为登录表单的主线程,那么缺少什么或者如果我以错误的方式实现?

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); 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.这有点说明,但是当您使用Task.Run时,传入的操作将被安排到默认任务调度程序,如果您没有定义任何默认线程池,那么ThreadPool的一个线程将在您的主 UI 线程自由等待另一个 UI 操作时开始工作。 So there shouldn't be freezing on your UI application because of the fact above .因此,由于上述事实,您的 UI 应用程序不应该冻结

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 ).如果它看起来像冻结,您可能通过您的Visual Studio使用 F5 运行应用程序(如果 F5 表示在您的热键配置中开始调试)。 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.因为Console.WriteLine将在 IDE 某处的“输出”window 上吐出所有索引值,并使对应用程序的操作无响应,即使您在应用程序中的 UI 实际上并未冻结。

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.如果您仍想通过Visual Studio运行应用程序或直接执行.exe ,请尝试在 IDE 之外运行您的应用程序,只需CTRL + F5 (无需调试即可启动)。 Then I guess you can see your UI working fine.然后我猜你可以看到你的 UI 工作正常。

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.您也不会对任务的结果做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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