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 WaitAndReturnPrice
to 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 ( ).