【发布时间】:2019-10-11 00:38:04
【问题描述】:
我想创建一个简单的异步弹出窗口应用程序,窗口窗体最后是 showdialog。 但是当我运行程序时,程序自动退出而没有错误 你能帮我解决吗,这是我的代码
private static string pridbUser = "user";
private static string pridbPwd = "abc123";
public void run()
{
string cnnStr = @"Data Source=localhost;Initial Catalog=sampledb;User ID=" + pridbUser + ";Password=" + pridbPwd + ";MultipleActiveResultSets=true";
string sql = "SELECT * FROM [TABLE1]";
using (SqlConnection sqlcnn = new SqlConnection(cnnStr))
{
sqlcnn.Open();
var tskJob = CreateTableAsync(sql, sqlcnn);
using (frmUI ui = new frmUI())
{
Task.WhenAll(tskJob);
ui.BindControl(tskJob.Result.DefaultView);
ui.ShowDialog();
}
}
}
private async Task<DataTable> CreateTableAsync(string sql, SqlConnection dbCnn)
{
using (SqlCommand _c = new SqlCommand(sql, dbCnn))
{
DataTable dt = new DataTable();
dt.Load(await _c.ExecuteReaderAsync());
return dt;
}
}
修改,嗨,谢谢你的评论,然后我重写了异步作业,但结果不是我想要的,下面的代码:
private static string pridbUser = "user";
private static string pridbPwd = "abc123";
public void run()
{
string cnnStr = @"Data Source=localhost;Initial Catalog=sampledb;User ID=" + pridbUser + ";Password=" + pridbPwd + ";MultipleActiveResultSets=true";
string sql = "SELECT * FROM [TABLE1]";
using (SqlConnection sqlcnn = new SqlConnection(cnnStr))
{
sqlcnn.Open();
Console.WriteLine("Create Table with Asyn mode");
var tskJob = CreateTableAsync(sql, sqlcnn);
using (frmUI ui = new frmUI())
{
Console.WriteLine("Create Form Complete");
Task.WhenAll(tskJob);
ui.BindControl(tskJob.Result.DefaultView);
ui.ShowDialog();
}
}
}
private async Task<DataTable> CreateTableAsync(string sql, SqlConnection dbCnn)
{
Console.WriteLine("Start to Create Table")
using (SqlCommand _c = new SqlCommand(sql, dbCnn))
{
DataTable dt = new DataTable();
dt.Load(await _c.ExecuteReaderAsync());
Console.WriteLine("Delay 5 second")
Thread.Sleep(5000); // delay 5 seconds
Console.WriteLine("End Delay")
return dt;
}
}
运行结果是:
Create Table with Asyn mode
Start to Create Table
Delay 5 second
End Delay and Return
Create the Form Complete
Bind Control
但我的预期结果应该是
Create Table with Asyn mode
Start to Create Table
Create the Form Complete
Delay 5 second <-- as it should not wait 5 second and then run form in async process
End Delay and Return
Bind Control
你有什么好的建议
【问题讨论】:
-
我认为您在没有
await的情况下调用该函数,是吗?您可以在其中包含调用它的代码吗? -
async void run()是一个火和忘记。它将在主线程的单独线程上执行,而不是等待。 -
@Nkosi 我没有注意到它是
void,然后解释它。 -
嗨,调用这个类只是 static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SampleApps2.SerClass1 cls = new SampleApps2.SerClass1(); cls.run();返回; }
标签: c# async-await desktop-application