我有一个 WPF 应用程序,用户输入搜索名称/字符串并根据复选框选择 server1 或 server2,然后单击搜索按钮。根据复选框选择,它将查询和搜索第一台服务器或第二台服务器,但也可以选择同时搜索/查询两个服务器。 我当前在事件处理程序中使用 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 语句,该语句基本上只是检查其他服务器复选框是否已启用,并且基本上根据 clientctx.ExecuteQuery(); 执行相同的操作;唯一的区别是查询略有不同,变量名称也略有不同(用于存储结果)。
现在,如果我需要同时运行这两个 CamlQuery 怎么办?我应该查看 Parallel.Invoke 实现吗?或者任务和线程?这里推荐的行动方案是什么?
基本上我想要:
1) 检查两个复选框是否都被选中 2)如果它们同时执行两个查询 3)返回结果
因此,如果有人对解决此问题的最佳方法有建议,我将不胜感激。
亲切的问候
最佳答案
如果您使用的是 SharePoint,则有一个自然异步 API 可以实现此目的,ExecuteQueryAsync
:
public override void ExecuteQueryAsync(
ClientRequestSucceededEventHandler succeededCallback,
ClientRequestFailedEventHandler failedCallback
)
首先,您需要用 TaskCompletionSource 将其包裹起来作为一个单独的方法(我们称之为 ExecuteQueryTapAsync),使用 succeededCallback
和 failedCallback
返回一个 Task
。更多信息:How to: Wrap EAP Patterns in a Task , Tasks and the Event-based Asynchronous Pattern .
然后您可以并行运行两个查询,如下所示。您需要使按钮点击处理程序异步
:
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/