aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/TransportMessage.cs
blob: 90e600a06b612133e00e1454e80a7208e87d5425 (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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.PMR;

namespace Tango.Transport
{
    /// <summary>
    /// Represents a generic transport message.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="Tango.Transport.TransportMessageBase" />
    public class TransportMessage<T> : TransportMessageBase
    {
        private TaskCompletionSource<T> _completionSource;

        public Action<T> ResponseCallback { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransportMessage{T}"/> class.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="message">The message.</param>
        /// <param name="direction">The direction.</param>
        /// <param name="toBytes">To bytes.</param>
        /// <param name="completionSource">The completion source.</param>
        public TransportMessage(ITransportAdapter adapter, string token, object message, TransportMessageDirection direction, Func<byte[]> toBytes, TaskCompletionSource<T> completionSource) : base(adapter, token, message, direction, toBytes)
        {
            _completionSource = completionSource;
        }

        /// <summary>
        /// Notifies the message observer of the new result.
        /// </summary>
        /// <param name="result">The result.</param>
        public override void SetResult(object result, bool completed)
        {
            _completionSource.SetResult((T)result);
        }

        /// <summary>
        /// Notifies the message observer of an exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        public override void SetException(Exception ex)
        {
            _completionSource.SetException(ex);
        }

        /// <summary>
        /// Invokes the response callback.
        /// </summary>
        /// <param name="response">The response.</param>
        public override void InvokeResponseCallback(object response, bool completed)
        {
            ResponseCallback((T)response);
        }
    }
}