Created
July 27, 2016 20:05
-
-
Save Mart-Bogdan/28ed5c7f3d86d49517c195bddc6baf1c to your computer and use it in GitHub Desktop.
TaskCompletionSource sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using System.Threading.Tasks; | |
using Newtonsoft.Json.Linq; | |
using SamuelServer.Common.Communication; | |
using SamuelServer.Common.Communication.Interfaces; | |
using SamuelServer.Common.Exceptions; | |
using SamuelServer.Common.Interfaces; | |
using SamuelServer.Common.Wrappers; | |
using SamuelServer.IOCCommon.Attributes; | |
namespace SamuelServer.BL.Services | |
{ | |
[SingletonScope] | |
public class CommandExecution : ICommandExecution | |
{ | |
private readonly ICommunication _communication; | |
public CommandExecution(ICommunication communication) | |
{ | |
_communication = communication; | |
_communication.MessageRecived += MessageReceived; | |
} | |
private ConcurrentDictionary<Guid, TaskCompletionSource<CommandResponse>> _taskDictionary = new ConcurrentDictionary<Guid, TaskCompletionSource<CommandResponse>>(); | |
public Task<CommandResponse> ExecuteCommand(Guid idAgent, string commandName, JToken parameter) | |
{ | |
Guid reqId = Guid.NewGuid(); | |
//создаем запрос на выполнение комманды | |
var commandRequest = new CommandRequest( | |
reqId, | |
commandName, | |
parameter | |
); | |
var commandRunRequest = new ServerRequest(commandRequest); | |
//асинхронный источник | |
var tcs = new TaskCompletionSource<CommandResponse>(); | |
//Add elements to TaskDictionary | |
_taskDictionary.TryAdd(reqId, tcs); | |
try | |
{ | |
//делаем запросс на агент | |
_communication.Send(idAgent, commandRunRequest); | |
} | |
catch (SamuelMessagingException exception) | |
{ | |
throw new CommandExecutionException("Error while sending command to agent", exception); | |
} | |
return tcs.Task; | |
} | |
public void MessageReceived(Guid agentId, AgentResponse response) | |
{ | |
try | |
{ | |
foreach (CommandResponse commandResponse in response.ResponseList) | |
{ | |
//if (Log.IsDebugEnabled) | |
//Log.Trace(String.Format("Received command responce({1}) from agent {0} ", agentId, | |
//commandResponse.Id)); | |
TaskCompletionSource<CommandResponse> completionSource; | |
if (_taskDictionary.TryRemove(commandResponse.Id, out completionSource)) | |
{ | |
completionSource.SetResult(commandResponse); | |
} | |
else | |
{ | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment