16
16
namespace HiveMQtt . MQTT5 . Packets ;
17
17
18
18
using System . IO ;
19
-
19
+ using HiveMQtt . Client . Events ;
20
20
using HiveMQtt . Client . Options ;
21
21
using HiveMQtt . MQTT5 . Types ;
22
22
@@ -43,6 +43,14 @@ public SubscribePacket(SubscribeOptions options, ushort packetIdentifier, Dictio
43
43
{
44
44
this . Properties . UserProperties = userProperties ;
45
45
}
46
+
47
+ // Setup the TaskCompletionSource so users can simply call
48
+ //
49
+ // await SubscribePacket.OnCompleteTCS
50
+ //
51
+ // to wait for the subscribe transaction to complete.
52
+ this . OnComplete += ( sender , args ) => this . OnCompleteTCS . SetResult ( args . SubAckPacket ) ;
53
+
46
54
}
47
55
48
56
/// <summary>
@@ -53,6 +61,46 @@ public SubscribePacket(SubscribeOptions options, ushort packetIdentifier, Dictio
53
61
/// <inheritdoc/>
54
62
public override ControlPacketType ControlPacketType => ControlPacketType . Subscribe ;
55
63
64
+
65
+ /// <summary>
66
+ /// Valid for outgoing Subscribe packets. An event that is fired after the the subscribe transaction is complete.
67
+ /// </summary>
68
+ public event EventHandler < OnSubAckReceivedEventArgs > OnComplete = new ( ( client , e ) => { } ) ;
69
+
70
+ internal virtual void OnCompleteEventLauncher ( SubAckPacket packet )
71
+ {
72
+ if ( this . OnComplete != null && this . OnComplete . GetInvocationList ( ) . Length > 0 )
73
+ {
74
+ var eventArgs = new OnSubAckReceivedEventArgs ( packet ) ;
75
+ Logger . Trace ( "SubscribePacket.OnCompleteEventLauncher" ) ;
76
+ _ = Task . Run ( ( ) => this . OnComplete ? . Invoke ( this , eventArgs ) ) . ContinueWith (
77
+ t =>
78
+ {
79
+ if ( t . IsFaulted )
80
+ {
81
+ if ( t . Exception is not null )
82
+ {
83
+ Logger . Error ( "SubscribePacket.OnCompleteEventLauncher exception: " + t . Exception . Message ) ;
84
+ foreach ( var ex in t . Exception . InnerExceptions )
85
+ {
86
+ Logger . Error ( "SubscribePacket.OnCompleteEventLauncher inner exception: " + ex . Message ) ;
87
+ }
88
+ }
89
+ }
90
+ } ,
91
+ TaskScheduler . Default ) ;
92
+ }
93
+ }
94
+
95
+ /// <summary>
96
+ /// Gets the awaitable TaskCompletionSource for the subscribe transaction.
97
+ /// <para>
98
+ /// Valid for outgoing subscribe packets. A TaskCompletionSource that is set when the subscribe transaction is complete.
99
+ /// </para>
100
+ /// </summary>
101
+ public TaskCompletionSource < SubAckPacket > OnCompleteTCS { get ; } = new ( ) ;
102
+
103
+
56
104
/// <summary>
57
105
/// Encode this packet to be sent on the wire.
58
106
/// </summary>
0 commit comments