我只想完成任务

问题描述 投票:0回答:1

嘿,我一整天都在想办法解决这个问题。 我只想在加载数据时显示一个启动窗口。我还想检查用户是否需要登录。一切都会完成,但任务永远不会标记为完成。

public ProgramMain()
{
InitializeComponent();
LoadDataAsync().Wait();
_viewPageManager = new ViewPageManager(MainTabControl);
}

protected async Task LoadDataAsync()
{
StartUp.StartUpForm progressForm = new StartUp.StartUpForm();
progressForm.Show();
// 'await' long-running method by wrapping inside Task.Run
await Task.Run(() =>
{                
    AppSetting setting = new AppSetting();
    SqlHelper helper = new SqlHelper(setting.GetConnectionString("cn"));
    if(!helper.HandShake())
    {
        UserLogin userLogin = new UserLogin();
        if(userLogin.ShowDialog() == DialogResult.OK)
        {
            MessageBox.Show("Logged In");
            return Task.FromResult(true);
        }
        else
        {
            return Task.FromResult(false);
        }
    }
    else
    {
        return Task.FromResult(true);
    }

}

).ContinueWith(new Action<Task>(task =>
{
    //if (this.IsHandleCreated)
    // Close modal dialog
    // No need to use BeginInvoke here
    //   because ContinueWith was called with TaskScheduler.FromCurrentSynchronizationContext()
    progressForm.Close();

}), TaskScheduler.FromCurrentSynchronizationContext());


}
c# multithreading asynchronous task
1个回答
0
投票

由于这一行,您陷入了僵局:

LoadDataAsync().Wait();

当您从 UI 线程运行没有

await
的任务,而是使用
.Wait()
时,将会产生死锁。新线程完成后,尝试与原始 UI 线程通信,表示它已完成,但 UI 线程被冻结等待它完成。

使用

await
可防止 UI 线程冻结,同时仍等待新线程完成。

只需将您的

ProgramMain
方法更改为异步任务并使用等待:

public async Task ProgramMain()
{
    InitializeComponent();
    await LoadDataAsync();
    _viewPageManager = new ViewPageManager(MainTabControl);
}

如果仍然遇到问题,请尝试删除

ContinueAwait
并将
progressForm.Close()
放在最后的
Task.Run()
之外。

© www.soinside.com 2019 - 2024. All rights reserved.