我有一个包含多个SQL查询的网格,我希望用户在双击网格中的一行时允许其执行。我希望用户能够同时运行多个查询。
我有一个小的表格,带有进度条和每个查询的计时器。表单在运行查询时显示,并在查询完成后显示完整。
下面是我的代码,看来返回数据的方法正在阻塞。我之前从未使用过sync / threads / tasks
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationTokenHook hook = new CancellationTokenHook(cts);
CancellationToken token = cts.Token;
//this.waitFormActivator.ShowWaitForm(true, true);
//this.waitFormActivator.SetWaitFormObject(hook);
Exception exception = null;
try
{
progressControl.Start();
Task<Dataset> t = Test(command.CommandText, token, saveFileDialog1.FileName);
var result = await t;
progressControl.Stop();
}
catch (Exception ex)
{
//success = false;
exception = ex;
//return null;
}
}
我希望查询彼此独立运行,但是当前下一个查询正在等待上一个查询结束。
答案 0 :(得分:0)
这段代码是为了回答您的问题
List<Task> tasks = new List<Task>();
tasks.Add(new Task(() => { action1 }));
tasks.Add(new Task(() => { action2 }));
tasks.Add(new Task(() => { action3 }));
tasks.Add(new Task(() => { action4 }));
Task.WhenAll(tasks);
在您的上下文中,应该像这样:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationTokenHook hook = new CancellationTokenHook(cts);
CancellationToken token = cts.Token;
his.waitFormActivator.ShowWaitForm(true, true);
his.waitFormActivator.SetWaitFormObject(hook);
eption exception = null;
try
{
progressControl.Start();
List<Task<Dataset>> tasks = new List<Task<DataSert>>();
Task<Dataset> t1 = Test(command.CommandText, token, saveFileDialog1.FileName);
Task<Dataset> t2 = Test(command.CommandText, token, saveFileDialog1.FileName);
Task<Dataset> t3 = Test(command.CommandText, token, saveFileDialog1.FileName);
Task<Dataset> t4 = Test(command.CommandText, token, saveFileDialog1.FileName);
tasks.Add(t1);
tasks.Add(t2);
tasks.Add(t3);
tasks.Add(t4);
var result = Task.WhenAll(tasks);
progressControl.Stop();
}
catch (Exception ex)
{
//success = false;
exception = ex;
//return null;
}
}