繁体   English   中英

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

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

我需要在任务中调用 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;
}

后端代码:

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

所以任何人都可以指导我解决这个问题。

Console.WriteLine(i);

是您的代码中唯一高度可疑的东西。 这有点说明,但是当您使用Task.Run时,传入的操作将被安排到默认任务调度程序,如果您没有定义任何默认线程池,那么ThreadPool的一个线程将在您的主 UI 线程自由等待另一个 UI 操作时开始工作。 因此,由于上述事实,您的 UI 应用程序不应该冻结

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

如果您仍想通过Visual Studio运行应用程序或直接执行.exe ,请尝试在 IDE 之外运行您的应用程序,只需CTRL + F5 (无需调试即可启动)。 然后我猜你可以看到你的 UI 工作正常。

这是因为按钮单击事件处理程序正在等待任务(即它正在等待任务完成)。 您也不会对任务的结果做任何事情。

暂无
暂无

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

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