相关疑难解决方法(0)

具有指定结果的任务并行库WaitAny

我正在尝试编写一些代码,这些代码将使Web服务并行调用多个不同的服务器,因此TPL似乎是一个明显的选择.

只有我的一个Web服务调用将返回我想要的结果,而其他所有调用都不会.我正试图找出一种有效的方法,Task.WaitAnyTask匹配条件的第一个返回时,只有解锁.

我尝试过,WaitAny但无法确定过滤器的位置.我到目前为止:

public void SearchServers()
{
    var servers = new[] {"server1", "server2", "server3", "server4"};
    var tasks = servers
                 .Select(s => Task<bool>.Factory.StartNew(server => CallServer((string)server), s))
                 .ToArray();

    Task.WaitAny(tasks); //how do I say "WaitAny where the result is true"?

    //Omitted: cancel any outstanding tasks since the correct server has been found
}

private bool CallServer(string server)
{
    //... make the call to the server and return the result ...
}
Run Code Online (Sandbox Code Playgroud)

编辑:快速澄清,以防上面有任何混淆.我正在尝试执行以下操作:

  1. 对于每个服务器,启动a Task进行检查
  2. 或者,等到服务器返回true(最多只有1个服务器将返回true) …

c# task-parallel-library

13
推荐指数
1
解决办法
4850
查看次数

如何并行运行任务并选择满足C#中给定条件的第一个结果?

我希望并行运行三个任务.我希望检查完成的第一个任务的结果,并检查以确定结果是否良好.如果是,我取消所有其他任务并返回此结果,如果没有,我将等待下一个完成的任务并检查是否良好,如果是,则执行相同操作.(想想是良好的OutputDataType成员对一些简单的检查).

我继续这个,直到我获得一个结果很好的完成任务,或者所有任务返回的结果都不,在这种情况下我会返回null.

先感谢您.

using System;
using System.Threading;
using System.Threading.Tasks;
namespace myNamespace
{
    class Program
    {
        static void Main()
        {
            InputDataType data = getMyData();
            OutputDataType x = Foo(data);
        }   

        static OutputDataType Foo(InputDataType data)
        {
            Task<OutputDataType> task1 = null, task2 = null, taks3 = null;
            Task<OutPutDataType>[] TaskArray = { task1, task2, task3 };

            task1 = Task<SolutionInterpreters>.Factory.StartNew(() => RunFunc1(data));
            task2 = Task<SolutionInterpreters>.Factory.StartNew(() => RunFunc2(data));
            task3 = Task<SolutionInterpreters>.Factory.StartNew(() => RunFunc3(data));

            /*
            . …
Run Code Online (Sandbox Code Playgroud)

.net c# parallel-processing wait task-parallel-library

4
推荐指数
1
解决办法
289
查看次数