gpt4 book ai didi

c# - 在 WPF 事件中同时运行两个代码部分的推荐方法?

转载 作者:行者123 更新时间:2023-11-30 22:09:35 25 4
gpt4 key购买 nike

我有一个 WPF 应用程序,用户在其中输入搜索名称/字符串并根据复选框选择服务器 1 或服务器 2,然后点击搜索按钮。根据复选框的选择,它将查询和搜索第一台服务器或第二台服务器,但也可以选择同时搜索/查询两台服务器。我目前在事件处理程序内部设置了一个 if 语句和一个 else 语句,但我需要实现第三个条件,其中两个都被选中。

现在,在第三个控制语句中,我希望同时执行两个查询,但我不确定实现它的最佳方法是什么。

代码如下:

private void searchGzBTN_Click(object sender, RoutedEventArgs e)
{
NetworkCredential credentials = new NetworkCredential(usrBoxValue, pwdBoxValue, domainFuerNetCred);
if ((!string.IsNullOrEmpty(GzBoxValue)) && Handle(checkboxGz2010))
{
ListBox2010.Items.Clear();
using (ClientContext clientctx = new ClientContext(url2010BoxValue))
{

clientctx.Credentials = credentials;
List selektierteListe = clientctx.Web.Lists.GetByTitle(comboBoxValue);
CamlQuery query = new CamlQuery();
query.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Contains><FieldRef Name='GZ'/><Value Type='Text'>" + GzBoxValue + "</Value></Contains></Where></Query><ViewFields><FieldRef Name='BaseName' /><FieldRef Name='Title' /><FieldRef Name='Name' /><FieldRef Name='ID' /></ViewFields></View>"; //Viewfields noch einbauen

ListItemCollection GFGZListe = selektierteListe.GetItems(query);
clientctx.Load(GFGZListe);
clientctx.ExecuteQuery();

foreach (ListItem item in GFGZListe)
{
ListBox2010.Items.Add("" +item["FileleafRef"]);
}
GFGZListePass = GFGZListe;
}
}

如前所述,紧跟在 else 语句之后的是 else 语句,它基本上只是检查是否启用了其他服务器复选框,并且基本上根据 clientctx.ExecuteQuery(); 执行相同的操作;唯一的区别是查询略有不同,变量名称也略有不同(用于存储结果)。

现在如果我需要同时运行这两个 CamlQuery 怎么办?我应该查看 Parallel.Invoke 实现吗?或者任务和线程?这里推荐的行动方案是什么?

本质上我想要:

1) 检查两个复选框是否都被选中2)如果他们同时执行两个查询3)返回结果

因此,如果有人对解决此问题的最佳方法有任何建议,我将不胜感激。

亲切的问候

最佳答案

如果您使用的是 SharePoint,则有一个天然异步 API,ExecuteQueryAsync :

public override void ExecuteQueryAsync(
ClientRequestSucceededEventHandler succeededCallback,
ClientRequestFailedEventHandler failedCallback
)

首先,您需要用 TaskCompletionSource 包装它作为一个单独的方法(我们称之为 ExecuteQueryTapAsync)返回一个 Task,使用 succeededCallbackfailedCallback。更多信息:How to: Wrap EAP Patterns in a Task , Tasks and the Event-based Asynchronous Pattern .

然后您可以像下面这样并行运行两个查询。你需要让你的按钮点击处理程序async:

private async void searchGzBTN_Click(object sender, RoutedEventArgs e)
{
try
{
// ...

// server1
var query1 = ExecuteQueryTapAsync(clientctx);
// ...

// server2
var query2 = ExecuteQueryTapAsync(clientctx);
// ...

// asynchronously await both results
await Task.WhenAll(query1, query2);
// ...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

关于c# - 在 WPF 事件中同时运行两个代码部分的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21444803/

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