Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- public class RequestList
- {
- Dictionary<Guid, RequestMessage> requests;
- public RequestList()
- {
- requests = new Dictionary<Guid, RequestMessage>();
- }
- public void Add(RequestMessage request)
- {
- request.Status = MessageStatus.Pending;
- //Create a cancellation token source, this will be used to cancel a task
- request.RequestCancelToken = new CancellationTokenSource();
- requests.Add(request.MessageID, request);
- //Create and start a task and pass on the cancellation token to it
- var task = Task.Factory.StartNew(() =>
- //We also pass on the token to the operation for it access the token to check for
- //cancellation
- Process(request), request.RequestCancelToken.Token
- );
- }
- public void Cancel(RequestMessage request)
- {
- var dictRequestValue = (from x in requests
- where x.Key == request.MessageID
- select x).First().Value;
- dictRequestValue.RequestCancelToken.Cancel();
- dictRequestValue.Status = MessageStatus.Cancelled;
- }
- //This method contains the operation being executed by the task in parallel
- private static void Process(RequestMessage request)
- {
- request.Status = MessageStatus.Processing;
- CancellationToken token = request.RequestCancelToken.Token;
- //Check if cancellation is requested, using the token passed to the method
- //This check is for the case when cancellation might have been requested even before start of the
- //task
- if (token.IsCancellationRequested)
- {
- //This throws an OperationCanceledException if the token has had cancellation requested
- token.ThrowIfCancellationRequested();
- }
- //This simulates work
- var sw = new SpinWait();
- for (var i = 0; i < 1000; i++)
- {
- for (int j = 0; j < 50; j++)
- {
- sw.SpinOnce();
- }
- //Check for requested cancellation amidst execution logic
- if (token.IsCancellationRequested)
- {
- //This throws an OperationCanceledException if the token has had cancellation requested
- token.ThrowIfCancellationRequested();
- }
- }
- //This code is reached if the task gets to complete prior to a cancellation request
- request.Status = MessageStatus.Done;
- }
- }
Add Comment
Please, Sign In to add comment