aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/TransporterBase.cs
blob: d3d8730f0c7d548bf18cbd65023352dc3ed446eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Tango.DAL.Remote.DB
{
    using System;
    using System.Collections.Generic;
    
    public partial class CAT
    {
        public int ID { get; set; }
        public string GUID { get; set; }
        public System.DateTime LAST_UPDATED { get; set; }
        public string NAME { get; set; }
        public string MACHINE_GUID { get; set; }
        public string RML_GUID { get; set; }
        public string LIQUID_TYPE_GUID { get; set; }
        public byte[] DATA { get; set; }
    
        public virtual LIQUID_TYPES LIQUID_TYPES { get; set; }
        public virtual MACHINE MACHINE { get; set; }
        public virtual RML RML { get; set; }
    }
}
8 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
using Google.Protobuf;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Logging;
using Tango.PMR;
using Tango.PMR.Common;
using System.Reactive.Linq;
using System.ServiceModel;
using Tango.Transport.Encoders;
using Tango.PMR.Connection;
using Tango.Core.Threading;

namespace Tango.Transport
{
    /// <summary>
    /// Represents an <see cref="ITransporter"/> base class.
    /// </summary>
    /// <seealso cref="Tango.Transport.ITransporter" />
    public abstract class TransporterBase : ExtendedObject, ITransporter
    {
        private const int MESSAGE_TOKEN_LENGTH = 36;
        private ProducerConsumerQueue<TransportMessageBase> _sendingQueue;
        private ConcurrentList<TransportMessageBase> _pendingRequests;
        private ProducerConsumerQueue<byte[]> _arrivedResponses;
        private Thread _pushThread;
        private Thread _pullThread;
        private Thread _keepAliveThread;
        private ITransportAdapter _adapter;
        private Dictionary<String, PendingResponse> _pendingResponses;

        #region Events

        /// <summary>
        /// Occurs when a new request message has been received.
        /// </summary>
        public event EventHandler<MessageContainer> RequestReceived;

        /// <summary>
        /// Occurs when a new response message has been received.
        /// </summary>
        public event EventHandler<MessageContainer> PendingResponseReceived;

        /// <summary>
        /// Occurs when component state changes.
        /// </summary>
        public event EventHandler<TransportComponentState> StateChanged;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the <see cref="ITransportAdapter" /> used to read and write raw data.
        /// </summary>
        public ITransportAdapter Adapter
        {
            get { return _adapter; }
            set
            {
                var previous = _adapter;
                _adapter = value;
                OnAdapterChanged(previous, value);
                RaisePropertyChangedAuto();
            }
        }

        /// <summary>
        /// Gets or sets the transport encoder used to encode and decode tango messages.
        /// </summary>
        public ITransportEncoder Encoder { get; set; }

        private TransportComponentState _state;
        /// <summary>
        /// Gets the component state.
        /// </summary>
        public TransportComponentState State
        {
            get { return _state; }
            protected set
            {
                if (_state != value)
                {
                    _state = value;
                    OnStateChanged(_state);
                }
            }
        }

        /// <summary>
        /// Gets or sets the request timeout.
        /// </summary>
        public TimeSpan RequestTimeout { get; set; }

        private bool _useKeepAlive;
        /// <summary>
        /// Gets or sets a value indicating whether to use a keep alive mechanism.
        /// </summary>
        public bool UseKeepAlive
        {
            get { return _useKeepAlive; }
            set
            {
                _useKeepAlive = value;
                RaisePropertyChangedAuto();

                if (_useKeepAlive)
                {
                    LogManager.Log("KeepAlive is activated...");
                }
                else
                {
                    LogManager.Log("KeepAlive is deactivated.");
                }
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to auto respond to keep alive requests.
        /// </summary>
        public bool EnableKeepAliveAutoResponse { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the transporter will get in to a failed state if any adapter has failed.
        /// </summary>
        public bool FailsWithAdapter { get; set; }

        /// <summary>
        /// Gets the last failed state exception/reason.
        /// </summary>
        public Exception FailedStateException { get; private set; }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when the <see cref="Adapter"/> has changed.
        /// </summary>
        /// <param name="newAdapter">The adapter.</param>
        protected async virtual void OnAdapterChanged(ITransportAdapter oldAdapter, ITransportAdapter newAdapter)
        {
            if (oldAdapter != newAdapter)
            {
                _pendingRequests.Clear();
                _pendingResponses.Clear();
                _arrivedResponses = new ProducerConsumerQueue<byte[]>();
                _sendingQueue = new ProducerConsumerQueue<TransportMessageBase>();
            }

            if (oldAdapter != null)
            {
                oldAdapter.StateChanged -= OnAdapterStateChanged;
                oldAdapter.DataAvailable -= OnAdapterDataAvailable;
            }

            if (newAdapter != null)
            {
                LogManager.Log(String.Format("Adapter Changed: Type = {0}, Address = {1}, State = {2}", newAdapter.GetType().Name, newAdapter.Address, newAdapter.State));

                newAdapter.StateChanged -= OnAdapterStateChanged;
                newAdapter.DataAvailable -= OnAdapterDataAvailable;
                newAdapter.StateChanged += OnAdapterStateChanged;
                newAdapter.DataAvailable += OnAdapterDataAvailable;

                if (State == TransportComponentState.Connected && newAdapter.State == TransportComponentState.Disconnected)
                {
                    await newAdapter.Connect();
                }
            }
            else
            {
                LogManager.Log("Adapter Changed: null");
            }
        }

        /// <summary>
        /// Called when the current adapter state has changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        protected virtual void OnAdapterStateChanged(object sender, TransportComponentState e)
        {
            if (e == TransportComponentState.Failed && FailsWithAdapter)
            {
                OnFailed(new CommunicationException("The adapter has failed. Going into a failed state..."));
            }
        }

        /// <summary>
        /// Called when there is data available from the adapter.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="data">The data.</param>
        protected virtual void OnAdapterDataAvailable(object sender, byte[] data)
        {
            EnqueueMessageIn(data);
        }

        /// <summary>
        /// Called when the component has failed.
        /// </summary>
        /// <param name="ex">The ex.</param>
        protected virtual void OnFailed(Exception ex)
        {
            FailedStateException = ex;
            State = TransportComponentState.Failed;
            LogManager.Log(ex, "Transporter failed.");
            Disconnect().Wait();
        }

        /// <summary>
        /// Called when a new request has been received.
        /// </summary>
        /// <param name="container">The request.</param>
        protected virtual void OnRequestReceived(MessageContainer container)
        {
            RequestReceived?.Invoke(this, container);
        }

        /// <summary>
        /// Called when a new response has been received.
        /// </summary>
        /// <param name="container">The request.</param>
        protected virtual void OnResponseReceived(MessageContainer container)
        {
            PendingResponseReceived?.Invoke(this, container);
        }

        /// <summary>
        /// Called when the component state has changed.
        /// </summary>
        /// <param name="state">The state.</param>
        protected virtual void OnStateChanged(TransportComponentState state)
        {
            StateChanged?.Invoke(this, state);
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TransporterBase"/> class.
        /// </summary>
        public TransporterBase()
        {
            Encoder = new ProtoEncoder();
            _pendingResponses = new Dictionary<string, PendingResponse>();
            _sendingQueue = new ProducerConsumerQueue<TransportMessageBase>();
            _pendingRequests = new ConcurrentList<TransportMessageBase>();
            _arrivedResponses = new ProducerConsumerQueue<byte[]>();
            RequestTimeout = TimeSpan.FromSeconds(5);
            EnableKeepAliveAutoResponse = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransporterBase"/> class.
        /// </summary>
        /// <param name="adapter">The transport adapter.</param>
        public TransporterBase(ITransportAdapter adapter) : this()
        {
            Adapter = adapter;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Clears all message queues.
        /// </summary>
        public void ClearQueues()
        {
            _sendingQueue = new ProducerConsumerQueue<TransportMessageBase>();
            _pendingRequests = new ConcurrentList<TransportMessageBase>();
            _arrivedResponses = new ProducerConsumerQueue<byte[]>();
        }

        /// <summary>
        /// Connects the transport component.
        /// </summary>
        /// <returns></returns>
        public virtual async Task Connect()
        {
            if (Adapter != null)
            {
                await Adapter.Connect();
            }

            State = TransportComponentState.Connected;
            StartThreads();

            LogManager.Log("Transporter Connected...");
        }

        /// <summary>
        /// Disconnects the transport component.
        /// </summary>
        /// <returns></returns>
        public virtual async Task Disconnect()
        {
            State = TransportComponentState.Disconnected;

            try
            {
                if (_pullThread != null)
                {
                    _pullThread.Abort();
                    _pushThread.Abort();
                    _keepAliveThread.Abort();
                }
            }
            catch { }

            if (Adapter != null)
            {
                await Adapter.Disconnect();
            }
            LogManager.Log("Transporter Disconnected...");
        }

        /// <summary>
        /// Sends a request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="timeout">Optional timeout. If not specified will use the <see cref="RequestTimeout" />.</param>
        /// <returns></returns>
        public Task<IMessage> SendRequest(IMessage request, TimeSpan? timeout = null)
        {
            String requestName = request.GetType().Name;
            String responseName = requestName.Replace("Request", "Response");

            MessageContainer container = new MessageContainer();
            container.Token = Guid.NewGuid().ToString();
            container.Data = request.ToByteString();
            container.Timeout = timeout.HasValue ? (UInt32)timeout.Value.TotalMilliseconds : (UInt32)RequestTimeout.TotalMilliseconds;
            container.Type = MessageFactory.ParseMessageType(requestName);

            LogManager.Log("Queuing request message: " + requestName + " Token: " + container.Token, LogCategory.Debug);
            LogManager.Log("Expected response: " + responseName, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the request while transporter state is {State}."));
            }

            TaskCompletionSource<IMessage> source = new TaskCompletionSource<IMessage>();
            TransportMessage<IMessage> message = new TransportMessage<IMessage>(container.Token, request, TransportMessageDirection.Request, () => container.ToByteArray(), source);

            message.ActivateTimeout = () =>
            {
                TimeoutTask.StartNew(() =>
                {

                    if (!source.Task.IsCompleted)
                    {
                        TimeoutException ex = new TimeoutException("Request message: " + requestName + " had timed out after " + (timeout != null ? timeout.Value.TotalSeconds : RequestTimeout.TotalSeconds) + " seconds.");
                        LogManager.Log(ex);
                        LogManager.Log("Setting request task exception...", LogCategory.Debug);
                        source.SetException(ex);
                    }

                }, timeout != null ? timeout.Value : RequestTimeout);
            };

            EnqueueMessageOut(message);

            return source.Task;
        }

        /// <summary>
        /// Sends the response.
        /// </summary>
        /// <param name="response">The response.</param>
        /// <param name="token">The token.</param>
        /// <param name="completed">The completed.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Matching request token was not found!</exception>
        public Task SendResponse(IMessage response, string token, bool? completed = default(bool?), ErrorCode? errorCode = default(ErrorCode?), string errorMessage = null)
        {
            String responseName = response.GetType().Name;

            MessageContainer container = new MessageContainer();
            container.Token = token;
            container.Data = response.ToByteString();
            container.Type = MessageFactory.ParseMessageType(responseName);

            if (errorCode.HasValue)
            {
                container.Error = errorCode.Value;
            }

            if (errorMessage != null)
            {
                container.ErrorMessage = errorMessage;
            }

            if (completed.HasValue)
            {
                container.Completed = completed.Value;
            }

            return SendResponse(container);
        }

        /// <summary>
        /// Sends the request.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        public Task<MessageContainer> SendRequest(MessageContainer container)
        {
            String responseName = container.Type.ToString().Replace("Request", "Response");
            TimeSpan? timeout = GetContainerTimeoutOrDefault(container);

            LogManager.Log("Queuing request message: " + container.Type + " Token: " + container.Token, LogCategory.Debug);
            LogManager.Log("Expected response: " + responseName, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the request while transporter state is {State}."));
            }

            TaskCompletionSource<MessageContainer> source = new TaskCompletionSource<MessageContainer>();
            TransportMessage<MessageContainer> message = new TransportMessage<MessageContainer>(container.Token, container, TransportMessageDirection.Request, () => container.ToByteArray(), source);

            message.ActivateTimeout = () =>
            {
                TimeoutTask.StartNew(() =>
                {

                    if (!source.Task.IsCompleted)
                    {
                        TimeoutException ex = new TimeoutException("Request message: " + container.Type + " had timed out after " + (timeout != null ? timeout.Value.TotalSeconds : RequestTimeout.TotalSeconds) + " seconds.");
                        LogManager.Log(ex);
                        LogManager.Log("Setting request task exception...", LogCategory.Debug);
                        source.SetException(ex);
                    }

                }, timeout != null ? timeout.Value : RequestTimeout);

            };

            EnqueueMessageOut(message);

            return source.Task;
        }

        /// <summary>
        /// Sends the response.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Matching request token was not found!</exception>
        public Task SendResponse(MessageContainer container)
        {
            String token = container.Token;

            LogManager.Log("Queuing response message: " + container.Type, LogCategory.Debug);

            PendingResponse pendingResponse = null;

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the response while transporter state is {State}."));
            }

            LogManager.Log("Searching for matching request token: " + token, LogCategory.Debug);

            if (_pendingResponses.TryGetValue(token, out pendingResponse))
            {
                LogManager.Log("Found matching request token: " + token, LogCategory.Debug);

                if (!pendingResponse.IsContinuous)
                {
                    LogManager.Log("Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
                else if (container.Completed)
                {
                    LogManager.Log("Response completed. Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
            }
            else
            {
                //This should never happen.
                throw LogManager.Log(new InvalidOperationException("Matching request token was not found!"), LogCategory.Critical);
            }

            TaskCompletionSource<object> source = new TaskCompletionSource<object>();
            TransportMessage<object> message = new TransportMessage<object>(token, container, TransportMessageDirection.Response, () => container.ToByteArray(), source);
            EnqueueMessageOut(message);
            return source.Task;
        }

        /// <summary>
        /// Sends a request and expecting multiple response messages.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public IObservable<IMessage> SendContinuousRequest(IMessage request, TimeSpan? timeout = default(TimeSpan?))
        {
            String requestName = request.GetType().Name;
            String responseName = requestName.Replace("Request", "Response");

            MessageContainer container = new MessageContainer();
            container.Token = Guid.NewGuid().ToString();
            container.Data = request.ToByteString();
            container.Type = MessageFactory.ParseMessageType(requestName);
            container.Timeout = timeout.HasValue ? (UInt32)timeout.Value.TotalMilliseconds : (UInt32)RequestTimeout.TotalMilliseconds;
            container.Continuous = true;

            LogManager.Log("Queuing continuous request message: " + requestName + " Token: " + container.Token, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the request while transporter state is {State}."));
            }

            Subject<IMessage> subject = new Subject<IMessage>();

            LogManager.Log("Expected response: " + responseName, LogCategory.Debug);

            TransportMessage<IMessage> message = new TransportMessage<IMessage>(container.Token, request, TransportMessageDirection.Request, () => container.ToByteArray(), null)
            {
                IsContinuous = true,
                ContinuesResponseSubject = subject,
            };

            message.ActivateTimeout = () =>
            {

                TimeoutTask.StartNew(() =>
                {

                    if (!message.AtLeastOneResponseReceived)
                    {
                        TimeoutException ex = new TimeoutException("Request message: " + requestName + " had timed out after " + (timeout != null ? timeout.Value.TotalSeconds : RequestTimeout.TotalSeconds) + " seconds.");
                        LogManager.Log(ex);
                        LogManager.Log("Setting request exception...", LogCategory.Debug);
                        message.SetException(ex);
                    }

                }, timeout != null ? timeout.Value : RequestTimeout);

            };

            EnqueueMessageOut(message);

            return subject.AsObservable();
        }

        /// <summary>
        /// Sends a request.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="request">The request.</param>
        /// <param name="timeout">Optional timeout. If not specified will use the <see cref="RequestTimeout" />.</param>
        /// <returns></returns>
        public Task<TangoMessage<Response>> SendRequest<Request, Response>(TangoMessage<Request> request, TimeSpan? timeout = null) where Request : IMessage<Request> where Response : IMessage<Response>
        {
            LogManager.Log("Queuing request message: " + typeof(Request).Name + " Token: " + request.Container.Token, LogCategory.Debug);
            LogManager.Log("Expected response: " + typeof(Response).Name, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the request while transporter state is {State}."));
            }

            request.Container.Timeout = timeout.HasValue ? (UInt32)timeout.Value.TotalMilliseconds : (UInt32)RequestTimeout.TotalMilliseconds;

            TaskCompletionSource<TangoMessage<Response>> source = new TaskCompletionSource<TangoMessage<Response>>();
            TransportMessage<TangoMessage<Response>> message = new TransportMessage<TangoMessage<Response>>(request.Container.Token, request, TransportMessageDirection.Request, () => Encoder.Encode(request), source);

            message.ActivateTimeout = () =>
            {
                TimeoutTask.StartNew(() =>
                {

                    if (!source.Task.IsCompleted)
                    {
                        TimeoutException ex = new TimeoutException("Request message: " + typeof(Request).Name + " had timed out after " + (timeout != null ? timeout.Value.TotalSeconds : RequestTimeout.TotalSeconds) + " seconds.");
                        LogManager.Log(ex);
                        LogManager.Log("Setting request task exception...", LogCategory.Debug);
                        source.SetException(ex);
                    }

                }, timeout != null ? timeout.Value : RequestTimeout);
            };

            EnqueueMessageOut(message);

            return source.Task;
        }

        /// <summary>
        /// Sends a request and expecting multiple response messages.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="request">The request.</param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public IObservable<TangoMessage<Response>> SendContinuousRequest<Request, Response>(TangoMessage<Request> request, TimeSpan? firstTimeout = null, TimeSpan? continousTimeout = null) where Request : IMessage<Request> where Response : IMessage<Response>
        {
            LogManager.Log("Queuing continuous request message: " + typeof(Request).Name + " Token: " + request.Container.Token, LogCategory.Debug);

            Subject<TangoMessage<Response>> subject = new Subject<TangoMessage<Response>>();

            LogManager.Log("Expected response: " + typeof(Response).Name, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the request while transporter state is {State}."));
            }

            request.Container.Continuous = true;
            request.Container.Completed = false;

            request.Container.Timeout = firstTimeout.HasValue ? (UInt32)firstTimeout.Value.TotalMilliseconds : (UInt32)RequestTimeout.TotalMilliseconds;
            request.Container.ContinuousTimeout = continousTimeout.HasValue ? (UInt32)continousTimeout.Value.TotalMilliseconds : 0;

            TransportMessage<TangoMessage<Response>> message = new TransportMessage<TangoMessage<Response>>(request.Container.Token, request, TransportMessageDirection.Request, () => Encoder.Encode(request), null)
            {
                IsContinuous = true,
                ContinuesResponseSubject = subject,
            };

            message.ActivateTimeout = () =>
            {
                TimeoutTask.StartNew(() =>
                {

                    if (!message.AtLeastOneResponseReceived)
                    {
                        TimeoutException ex = new TimeoutException("Request message: " + typeof(Request).Name + " had timed out after " + (firstTimeout != null ? firstTimeout.Value.TotalSeconds : RequestTimeout.TotalSeconds) + " seconds.");
                        LogManager.Log(ex);
                        LogManager.Log("Setting request exception...", LogCategory.Debug);
                        message.SetException(ex);
                    }

                    if (continousTimeout != null)
                    {
                        Task.Factory.StartNew(async () =>
                        {
                            while (!message.Completed)
                            {
                                await Task.Delay(continousTimeout.Value).ContinueWith((y) =>
                                {
                                    if (!message.Completed)
                                    {
                                        if (DateTime.Now - message.LastResponseTime > continousTimeout.Value)
                                        {
                                            TimeoutException ex = new TimeoutException("Continuous request message: " + typeof(Request).Name + " had failed to provide a response for a period of " + (continousTimeout.Value.TotalSeconds) + " seconds and has timed out.");
                                            LogManager.Log(ex);
                                            LogManager.Log("Setting request exception...", LogCategory.Debug);
                                            message.SetException(ex);
                                            return;
                                        }
                                    }
                                });
                            }
                        });
                    }

                }, firstTimeout != null ? firstTimeout.Value : RequestTimeout);
            };

            EnqueueMessageOut(message);

            return subject.AsObservable();
        }

        /// <summary>
        /// Sends a continuous request.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        public IObservable<MessageContainer> SendContinuousRequest(MessageContainer container)
        {
            TimeSpan? timeout = GetContainerTimeoutOrDefault(container);
            TimeSpan? continuousTimeout = container.ContinuousTimeout > 0 ? TimeSpan.FromMilliseconds(container.ContinuousTimeout) : default(TimeSpan?);

            String requestName = container.Type.ToString();
            String responseName = requestName.Replace("Request", "Response");

            LogManager.Log("Queuing continuous request message: " + requestName + " Token: " + container.Token, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the request while transporter state is {State}."));
            }

            Subject<MessageContainer> subject = new Subject<MessageContainer>();

            LogManager.Log("Expected response: " + responseName, LogCategory.Debug);

            TransportMessage<MessageContainer> message = new TransportMessage<MessageContainer>(container.Token, container, TransportMessageDirection.Request, () => container.ToByteArray(), null)
            {
                IsContinuous = true,
                ContinuesResponseSubject = subject,
            };

            message.ActivateTimeout = () =>
            {
                TimeoutTask.StartNew(() =>
                {

                    if (!message.AtLeastOneResponseReceived)
                    {
                        TimeoutException ex = new TimeoutException("Request message: " + requestName + " had timed out after " + (timeout != null ? timeout.Value.TotalSeconds : RequestTimeout.TotalSeconds) + " seconds.");
                        LogManager.Log(ex);
                        LogManager.Log("Setting request exception...", LogCategory.Debug);
                        message.SetException(ex);
                    }

                    if (continuousTimeout != null)
                    {
                        Task.Factory.StartNew(async () =>
                        {
                            while (!message.Completed)
                            {
                                await Task.Delay(continuousTimeout.Value).ContinueWith((y) =>
                                {
                                    if (!message.Completed)
                                    {
                                        if (DateTime.Now - message.LastResponseTime > continuousTimeout.Value)
                                        {
                                            TimeoutException ex = new TimeoutException("Continuous request message: " + requestName + " had failed to provide a response for a period of " + (continuousTimeout.Value.TotalSeconds) + " seconds and has timed out.");
                                            LogManager.Log(ex);
                                            LogManager.Log("Setting request exception...", LogCategory.Debug);
                                            message.SetException(ex);
                                            return;
                                        }
                                    }
                                });
                            }
                        });
                    }

                }, timeout != null ? timeout.Value : RequestTimeout);
            };

            EnqueueMessageOut(message);

            return subject.AsObservable();
        }

        /// <summary>
        /// Sends a response.
        /// </summary>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="response">The response.</param>
        /// <returns></returns>
        public Task SendResponse<Response>(TangoMessage<Response> response) where Response : IMessage<Response>
        {
            return SendResponse<Response>(response, response.Container.Token);
        }

        /// <summary>
        /// Sends a response for the specified token.
        /// </summary>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="response">The response.</param>
        /// <param name="token">The token.</param>
        /// <param name="completed">The completed.</param>
        /// <param name="errorCode">The error code.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">Matching request token was not found!</exception>
        public Task SendResponse<Response>(TangoMessage<Response> response, String token, bool? completed = null, ErrorCode? errorCode = null, String errorMessage = null) where Response : IMessage<Response>
        {
            if (_pushThread == null || _pushThread.ThreadState == ThreadState.Aborted)
            {
                throw new InvalidOperationException("Transporter push thread is not in a running state.");
            }

            response.Container.Token = token;

            if (completed.HasValue)
            {
                response.Container.Completed = completed.Value;
            }

            if (errorCode.HasValue)
            {
                response.Container.Error = errorCode.Value;
            }

            if (!String.IsNullOrEmpty(errorMessage))
            {
                response.Container.ErrorMessage = errorMessage;
            }

            LogManager.Log("Queuing response message: " + typeof(Response).Name, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"Could not send the response while transporter state is {State}."));
            }

            PendingResponse pendingResponse = null;

            LogManager.Log("Searching for matching request token: " + token, LogCategory.Debug);

            if (_pendingResponses.TryGetValue(token, out pendingResponse))
            {
                LogManager.Log("Found matching request token: " + token, LogCategory.Debug);

                if (!pendingResponse.IsContinuous)
                {
                    LogManager.Log("Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
                else if (response.Container.Completed)
                {
                    LogManager.Log("Response completed. Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
            }
            else
            {
                //This should never happen.
                throw LogManager.Log(new InvalidOperationException("Matching request token was not found!"), LogCategory.Critical);
            }

            TaskCompletionSource<object> source = new TaskCompletionSource<object>();
            TransportMessage<object> message = new TransportMessage<object>(token, response, TransportMessageDirection.Response, () => Encoder.Encode(response), source);
            EnqueueMessageOut(message);
            return source.Task;
        }

        /// <summary>
        /// Sends a general error response agnostic to the type of request.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public Task SendErrorResponse(Exception exception, string token)
        {
            return SendResponse<ErrorResponse>(new ErrorResponse() { }, token, true, ErrorCode.GeneralError, exception.Message);
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Starts the pull and push threads.
        /// </summary>
        protected void StartThreads()
        {
            _pullThread = new Thread(PullThreadMethod);
            _pullThread.IsBackground = true;
            _pullThread.Start();

            _pushThread = new Thread(PushThreadMethod);
            _pushThread.IsBackground = true;
            _pushThread.Start();

            _keepAliveThread = new Thread(KeepAliveThreadMethod);
            _keepAliveThread.IsBackground = true;
            _keepAliveThread.Start();
        }

        /// <summary>
        /// Gets the container timeout or default.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        private TimeSpan? GetContainerTimeoutOrDefault(MessageContainer container)
        {
            return container.Timeout > 0 ? TimeSpan.FromMilliseconds(container.Timeout) : default(TimeSpan?);
        }

        /// <summary>
        /// Enqueues the message and releases the push wait handle.
        /// </summary>
        /// <param name="message">The message.</param>
        private void EnqueueMessageOut(TransportMessageBase message)
        {
            _sendingQueue.BlockEnqueue(message);
        }

        /// <summary>
        /// Enqueues the message and releases the pull wait handle.
        /// </summary>
        /// <param name="data">The data.</param>
        private void EnqueueMessageIn(byte[] data)
        {
            _arrivedResponses.BlockEnqueue(data);
        }

        #endregion

        #region Push Thread

        /// <summary>
        /// Push thread loop.
        /// </summary>
        private void PushThreadMethod()
        {
            try
            {
                while (State == TransportComponentState.Connected)
                {
                    TransportMessageBase message = _sendingQueue.BlockDequeue();

                    try
                    {
                        if (Adapter.State == TransportComponentState.Connected)
                        {
                            if (message.Token.Length != MESSAGE_TOKEN_LENGTH)
                            {
                                message.SetException(LogManager.Log(new InvalidOperationException("Invalid message token length: " + message.Token)));
                                continue;
                            }

                            LogManager.Log("Sending message on adapter: " + Adapter.Address + "...", LogCategory.Debug, message.Message);

                            if (message.Direction == TransportMessageDirection.Request)
                            {
                                lock (_pendingRequests)
                                {
                                    _pendingRequests.Add(message);
                                }
                            }

                            Adapter.Write(message.Serialize());

                            message.ActivateTimeout?.Invoke();

                            LogManager.Log("Message sent on adapter: " + Adapter.Address + "...", LogCategory.Debug, message.Message);
                        }
                        else
                        {
                            if (message.Direction == TransportMessageDirection.Request)
                            {
                                message.SetException(LogManager.Log(new InvalidOperationException("Could not send message " + message.Message.GetType().Name + ". Adapter is disconnected.")));
                            }
                        }

                        if (message.Direction == TransportMessageDirection.Response)
                        {
                            message.SetResult(true, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        message.SetException(ex);
                    }
                }
            }
            catch (ThreadAbortException)
            {
                LogManager.Log("Push thread has been aborted.");
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }
        }

        #endregion

        #region Pull Thread

        /// <summary>
        /// Pull thread loop.
        /// </summary>
        private void PullThreadMethod()
        {
            try
            {
                while (State == TransportComponentState.Connected)
                {
                    byte[] data = _arrivedResponses.BlockDequeue();

                    LogManager.Log("Message received on adapter: " + Adapter.Address, LogCategory.Debug);

                    LogManager.Log("Parsing message container...", LogCategory.Debug);
                    MessageContainer container = Encoder.DecodeContainer(data);

                    LogManager.Log("Message was identified as " + container.Type + ".", LogCategory.Debug);

                    if (container.Token.Length != MESSAGE_TOKEN_LENGTH)
                    {
                        LogManager.Log("Invalid message token length received: " + container.Token, LogCategory.Error);
                        continue;
                    }

                    LogManager.Log("Searching for pending request token: " + container.Token, LogCategory.Debug);

                    TransportMessageBase request = null;
                    lock (_pendingRequests)
                    {
                        request = _pendingRequests.ToList().SingleOrDefault(x => x.Token == container.Token);
                    }

                    if (request != null)
                    {
                        LogManager.Log("Found pending request: " + (request.Message.GetType().IsGenericType ? request.Message.GetType().GetGenericArguments()[0].Name : request.Message.GetType().Name), LogCategory.Debug);

                        if (!request.IsContinuous)
                        {
                            LogManager.Log("Pending request was identified as 'single response'. Removing pending request.", LogCategory.Debug);

                            _pendingRequests.Remove(request);

                            try
                            {
                                if (container.Error == ErrorCode.None)
                                {
                                    var message = Encoder.Decode(data);
                                    LogManager.Log("Parsing inner response message and setting pending request task result...", LogCategory.Debug, message);
                                    request.SetResult(message, true);
                                    LogManager.Log("Message enquirer released...", LogCategory.Debug);
                                }
                                else
                                {
                                    request.SetException(LogManager.Log(new ResponseErrorException(container), LogCategory.Warning));
                                }
                            }
                            catch (Exception ex)
                            {
                                request.SetException(LogManager.Log(ex, "Error parsing response message."));
                            }
                        }
                        else
                        {
                            LogManager.Log("Pending request was identified as 'continuous response'. keeping pending request.", LogCategory.Debug);

                            try
                            {
                                if (container.Error == ErrorCode.None)
                                {
                                    var message = Encoder.Decode(data);

                                    LogManager.Log("Parsing inner response message and invoking continuous response callback...", LogCategory.Debug, message);

                                    if (container.Completed)
                                    {
                                        LogManager.Log("Continuous sequence completed.", LogCategory.Debug);
                                        _pendingRequests.Remove(request);
                                    }
                                    request.SetResult(message, container.Completed);
                                }
                                else if (container.Error == ErrorCode.ContinuousResponseAborted)
                                {
                                    String m = "Continuous response " + container.Type + " has been aborted: " + container.Error.ToString();
                                    LogManager.Log(m, LogCategory.Info);
                                    _pendingRequests.Remove(request);
                                    request.SetException(new ContinuousResponseAbortedException(m));
                                }
                                else
                                {
                                    LogManager.Log("Continuous response has returned with error: " + container.Error.ToString(), LogCategory.Warning);
                                    _pendingRequests.Remove(request);
                                    request.SetException(new ResponseErrorException(container));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, "Error parsing response message.");
                            }
                        }

                        try
                        {
                            Task.Factory.StartNew(() => OnResponseReceived(container));
                        }
                        catch
                        {
                            //Ignore any exceptions that may raise on the client side..
                        }
                    }
                    else
                    {
                        if (container.Type.ToString().EndsWith("Response"))
                        {
                            LogManager.Log(String.Format("A response message with no awaiting request was identified. {0}, Token: {1}. Message ignored.", container.Type, container.Token), LogCategory.Warning);
                            continue;
                        }

                        LogManager.Log("Message was identified as a new request message: " + container.Type.ToString(), LogCategory.Debug);

                        try
                        {
                            LogManager.Log("Saving request token: " + container.Token, LogCategory.Debug);
                            _pendingResponses.Add(container.Token, new PendingResponse(container.Continuous));

                            if (container.Type == MessageType.KeepAliveRequest && EnableKeepAliveAutoResponse)
                            {
                                LogManager.Log("Submitting keep alive response...", LogCategory.Debug);
                                SendResponse<KeepAliveResponse>(new KeepAliveResponse(), container.Token);
                            }
                            else
                            {
                                LogManager.Log("Invoking RequestReceived event...", LogCategory.Debug, container);

                                try
                                {
                                    Task.Factory.StartNew(() => OnRequestReceived(container));
                                }
                                catch
                                {
                                    //Ignore any exceptions that may raise on the client side..
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex);
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
                LogManager.Log("Pull thread has been aborted.");
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }
        }

        #endregion

        #region Keep Alive Thread

        /// <summary>
        /// Responsible for sending keep alive messages.
        /// </summary>
        private void KeepAliveThreadMethod()
        {
            bool aborted = false;

            try
            {
                Thread.Sleep(2000);

                while (State == TransportComponentState.Connected)
                {
                    try
                    {
                        Thread.Sleep(2000);

                        if (UseKeepAlive)
                        {
                            if (_arrivedResponses.Count == 0)
                            {
                                var response = SendRequest<KeepAliveRequest, KeepAliveResponse>(new KeepAliveRequest(), TimeSpan.FromSeconds(2)).Result;
                            }
                            else
                            {
                                LogManager.Log("Keep alive request was skipped due to busy response queue.", LogCategory.Debug);
                            }
                        }
                    }
                    catch (Exception ex) when (ex is TimeoutException || ex is AggregateException)
                    {
                        if (State != TransportComponentState.Connected || aborted) return;

                        if (UseKeepAlive)
                        {
                            OnFailed(new KeepAliveException("The transporter has not received a KeepAlive response within the given time."));
                            return;
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        aborted = true;
                        LogManager.Log("KeepAlive thread has been aborted.");
                        return;
                    }
                    catch (Exception ex)
                    {
                        if (State != TransportComponentState.Connected || aborted) return;

                        if (UseKeepAlive)
                        {
                            OnFailed(ex);
                            return;
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
                LogManager.Log("KeepAlive thread has been aborted.");
            }
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return this.GetType().Name + ", Adapter: " + (Adapter != null ? Adapter.ToString() : "Null") + ", Encoder: " + (Encoder != null ? Encoder.ToString() : "Null");
        }

        #endregion

        #region Dispose

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Disconnect().Wait();
            State = TransportComponentState.Disposed;
        }

        #endregion
    }
}