Launching Parallel ForEach with timeouts

I have a set of trading objects, and each of them has 2 properties - spot price and forward price. I need to set the spot price property and the forward price in the background, as they get these prices from third-party services, which are slow. I only need to calculate the forward price if the selected price is received successfully or the spot price is received within a certain period of time.

Here is the code:

public class Trade
{
    public double SpotPrice { get; set; }
    public double ForwardPrice { get; set; }
}

static void Main(string[] args)
{
    var trades = new List<Trade> 
    {
        new Trade(), new Trade(), new Trade(), new Trade()
    };

    Parallel.ForEach(trades, (trade) =>
    {
        var pipeline = Task.Factory.StartNew<Trade>(() =>
        {
            trade.SpotPrice = WaitAndReturnPrice(TimeSpan.FromSeconds(2));
            Console.WriteLine("Spot Price:" + trade.SpotPrice);
            return trade;

        }).ContinueWith(t =>
        {
            var tradeObject = t.Result;

            tradeObject.ForwardPrice = WaitAndReturnPrice(TimeSpan.FromSeconds(2));
            Console.WriteLine("Forward Price:" + trade.ForwardPrice);
        });
    });
    Console.ReadLine();
}

static Random random = new Random();

private static double WaitAndReturnPrice(TimeSpan fromSeconds)
{
    Thread.Sleep(fromSeconds);
    return random.NextDouble();
}      

I added a method WaitAndReturnPriceto simulate that prices are obtained with a subsequent delay.

I encounter several problems with this approach, mainly due to a lack of my understanding of TPL. Problems:

  • ? , Spot 2 .

  • , , ?

  • 1 2 1 , , ?

?

, .NET4.0 ( ).

+4
1

, :

foreach (var trade in trades) {
  ThreadPool.QueueUserWorkItem(new WaitCallback(FetchPrice), trade);
} 

. . . .

void FetchPrice(object tradeObj)
{
  var trade = (Trade)tradeObj;
  try {
    trade.SpotPrice = WaitAndReturnPrice(TimeSpan.FromSecond(2));
    // . . . compute forward price ...   
  } catch (TimeOutException) {
    // . . . compute forward price in case of time-out fetching the spot price...   
  } catch (Exception ex) {
    // ...handle other errors
  }
} 

- ( "TimeOutException`) , , , .

0

All Articles