通常我不发表文章,而是阅读并找到答案。
但这一次,尽管我发现了数十篇有关异步/等待问题的帖子,但似乎没有解决方案适合我的情况(或者至少我听不懂)。
我的代码真的很长,所以我没有将其完整地放在这里,但是看起来像这样: 我有一个正在数据库中编写的任务:
public async Task WatchSpool(Button buttonSend)
{
LoadOptions();
//SpoolWatcher spoolWatcher = new SpoolWatcher(this, buttonSend);
SpoolWatcher spoolWatcher = new SpoolWatcher(this);
spoolWatcher.OnSpoolWatcherException += OnSpoolWatcherException;
Task thread = new Task(spoolWatcher.Run);
spoolWatcherMustStop = false;
thread.Start();
//spoolWatcher.Run();
}
然后另一个计数数据库中特定表中的记录数:
public int CountWaitingRecords(string table)
{
int WaitingRecords = 0;
try
{
using (SqliteConnection connexion = new SqliteConnection("Filename = spool.db"))
{
connexion.Open();
using (SqliteCommand cmd = new SqliteCommand("SELECT COUNT(*) AS Count FROM " + table, connexion))
{
SqliteDataReader rs = cmd.ExecuteReader();
rs.Read();
WaitingRecords = rs.GetInt32(rs.GetOrdinal("Count"));
rs.Dispose();
cmd.Dispose();
connexion.Dispose();
}
}
}
catch(Exception ex)
{
return -1;
}
return WaitingRecords;
}
他们两个都在这里被称为
private async void buttonSendSelectedItems_Click(object sender, RoutedEventArgs e)
{
try
{
//things doing fine here…
//Start spoolWatcher
batigest = new Batigest(localFolder + "\\spool.db");
batigest.OnSpoolWatcherException += new OnSpoolWatcherExceptionHandler(batigest_OnSpoolWatcherException);
//Alternative code
//Task.Run(() => batigest.WatchSpool(Envoyer)).Wait();
//Actual code
Task task = batigest.WatchSpool(Envoyer);
await task;
//Another alternative code
//task.Wait();
//Here I count how many rows I've in my table
LocalDB localDB = new LocalDB(localFolder.Path.ToString() + "\\spool.db");
int count = localDB.CountWaitingRecords("MouvementStock");
if (count > 0)
{
Envoyer.Content = "Envoyer (" + count + ")";
Envoyer.IsEnabled = true;
}
else
{
Envoyer.Content = "Envoyé!";
}
//Other things doing fine here…
}
catch (Exception ex)
{
Envoyer.IsEnabled = true;
Envoyer.Content = "Erreur!";
InterpretException("InventoryView2.buttonSendSelectedItems_Click()", ex);
}
}
问题是:在开始计算数据库中的行数之前,我应该等待任务完成。 但是我不能成功。 因此,如果有人可以告诉我我在做什么错,我将不胜感激。
答案 0 :(得分:4)
这段代码有一些问题:
public async Task WatchSpool(Button buttonSend)
{
SpoolWatcher spoolWatcher = new SpoolWatcher(this);
spoolWatcher.OnSpoolWatcherException += OnSpoolWatcherException;
Task thread = new Task(spoolWatcher.Run);
thread.Start();
}
首先,Task
不是线程,因此将其命名为误导和错误的。
第二,必须避免使用Task
构造函数。假设SpoolWatcher.Run
不是Task
,则应使用Task.Run
:
Task runner = Task.Run(() => spoolWatcher.Run());
第三,也是最重要的是,您await
尚无完成的意愿,因此WatchSpool
几乎会立即返回。
public async Task WatchSpool(Button buttonSend)
{
SpoolWatcher spoolWatcher = new SpoolWatcher(this);
spoolWatcher.OnSpoolWatcherException += OnSpoolWatcherException;
await Task.Run(() => spoolWatcher.Run());
}
作为一般说明,Task
返回方法应带有Async后缀,因此应为WatchSpoolAsync
。