Dwarrowdelf.PipeConnection.GetMessageAsync C# (CSharp) Method

GetMessageAsync() public method

public GetMessageAsync ( ) : Task
return Task
		public async Task<Message> GetMessageAsync()
		{
			Message msg;

			if (TryGetMessage(out msg))
				return msg;

			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

			Action handler = () =>
			{
				tcs.TrySetResult(true);
			};

			this.NewMessageEvent += handler;

			if (TryGetMessage(out msg) == false)
			{
				await tcs.Task;

				if (TryGetMessage(out msg) == false)
				{
					Thread.MemoryBarrier();

					if (this.IsConnected == false)
						return null;

					throw new Exception();
				}
			}

			this.NewMessageEvent -= handler;

			return msg;
		}