并行独立等待任务完成Task.Wait(millisecondsTimeout)

时间:2016-08-23 11:56:38

标签: c# multithreading

我有应用程序,它在自己的线程中运行大约30个工作者。 每个工作人员将RabbitMQ队列的请求传递给MS Dynamic Axapta 4.0, 然后等待响应,然后将其返回到RabbitMQ队列。 我希望实现“请求超时”功能 - 如果AxaptaObject调用比超时值花费更多时间 然后返回消息“请求超时”并跳过请求结果。 所以我为远程请求调用做了一些包装。

逻辑类似于以下代码:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;

public class TestClass
{
    public static int count = 3;
    public static int timeout = 1000;

    private int id;

    public static void Main()
    {
        for (int i = 0; i < count; i++)
        {
            new TestClass(i);
        }
        Console.ReadLine();
    }

    public TestClass(int id)
    {
        this.id = id;
        new Thread(Work).Start();
    }

    public void Work()
    {
        Stopwatch s = Stopwatch.StartNew();
        Task<int> t = Task<int>.Factory.StartNew(RemoteRequest);

        bool waitSuccess = t.Wait(timeout);

        s.Stop();
        string result;
        if (waitSuccess)
        {
            result = t.Result.ToString();
        }
        else
        {
            result = "timeout";
        }
        Console.WriteLine("TestClass id={0} finished remote request in {1}ms with result={2}", id, s.ElapsedMilliseconds, result);        
    }

    public int RemoteRequest()
    {
        // Dynamics AX 4.0 Microsoft.Dynamics.BusinessConnectorNet.AxaptaObject.Call()
        Console.WriteLine("TestClass id={0} executing remote request...", id);
        // Do some work
        Thread.Sleep(500);
        return id * 2; // return some result
    }
}

结果:

TestClass id=0 executing remote request...
TestClass id=1 executing remote request...
TestClass id=0 finished remote request in 516ms with result=0
TestClass id=1 finished remote request in 512ms with result=2
TestClass id=2 executing remote request...
TestClass id=2 finished remote request in 1010ms with result=timeout

你能否告诉我为什么第3个任务时间比Sleep()参数长两倍? (以及为什么消息“TestClass id = 2执行远程请求...”在前两个任务完成后出现)

@BugFinder指出:

  

显而易见的答案是因为一次只能运行2个请求。

所以问题是为什么一次只能运行2个请求?

0 个答案:

没有答案