gpt4 book ai didi

c# - 异步任务方法后触发回调

转载 作者:可可西里 更新时间:2023-11-01 07:53:46 25 4
gpt4 key购买 nike

我需要在 foreach 时触发回调循环已完成对 List<> 中每个项目的搜索.

private async void startSearchBtn_Click(object sender, EventArgs e)
{
await Search(files, selectTxcDirectory.SelectedPath, status);
}

private static async Task Search(List<string> files, string path, Label statusText)
{
foreach (string file in files)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(file);

statusText.Text = "Started scanning...";
using (XmlReader reader = XmlReader.Create(new StringReader(xmlDoc.InnerXml), new XmlReaderSettings() { Async = true }))
{
while (await reader.ReadAsync())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "LineName"))
{
Console.WriteLine(reader.ReadInnerXml());
}
}
}
}
}

这可能吗?如果可以,如何实现?

最佳答案

很简单,只要在参数中传递一个方法作为委托(delegate)即可。然后在需要的地方调用它。

private async void startSearchBtn_Click(object sender, EventArgs e)
{
await Search(files, selectTxcDirectory.SelectedPath, status, SearchCompleted); // <-- pass the callback method here
}

private static async Task Search(List<string> files, string path, Label statusText, Action<string> callback)
{
foreach (string file in files)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(file);

statusText.Text = "Started scanning...";
using (XmlReader reader = XmlReader.Create(new StringReader(xmlDoc.InnerXml), new XmlReaderSettings() { Async = true }))
{
while (await reader.ReadAsync())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "LineName"))
{
Console.WriteLine(reader.ReadInnerXml());
}
}
}

// Here you're done with the file so invoke the callback that's it.
callback(file); // pass which file is finished
}
}

private static void SearchCompleted(string file)
{
// This method will be called whenever a file is processed.
}

关于c# - 异步任务方法后触发回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com