// Copyright © 2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace CefSharp.Internals
{
///
/// Class to store TaskCompletionSources indexed by a unique id.
///
/// The type of the result produced by the tasks held.
public sealed class PendingTaskRepository
{
private readonly ConcurrentDictionary> pendingTasks =
new ConcurrentDictionary>();
//should only be accessed by Interlocked.Increment
private long lastId;
///
/// Creates a new pending task with a timeout.
///
/// The maximum running time of the task.
/// The unique id of the newly created pending task and the newly created .
public KeyValuePair> CreatePendingTask(TimeSpan? timeout = null)
{
var taskCompletionSource = new TaskCompletionSource();
var id = Interlocked.Increment(ref lastId);
pendingTasks.TryAdd(id, taskCompletionSource);
if (timeout.HasValue)
{
taskCompletionSource = taskCompletionSource.WithTimeout(timeout.Value, () => RemovePendingTask(id));
}
return new KeyValuePair>(id, taskCompletionSource);
}
///
/// Gets and removed pending task by id.
///
/// Unique id of the pending task.
///
/// The associated with the given id.
///
public TaskCompletionSource RemovePendingTask(long id)
{
TaskCompletionSource result;
pendingTasks.TryRemove(id, out result);
return result;
}
}
}