private T GetFreeResource(out long messageId)
        {
            lock (key1)
            {
                foreach (long key in messages.Keys)
                {
                    if (!messages[key].InUse)
                    {
                        messages[key].InUse = true;
                        messageId           = key;
                        return(messages[key].Resource);
                    }
                }

                //申请新资源
                T message = IResourceObject.Request();

                //申请资源失败
                if (message == null)
                {
                    messageId = GetNullResourceId();
                    return(null);
                }
                else
                {
                    ResourceWatcher <T> tag = new ResourceWatcher <T>(message, true);
                    long id = NewResourceId();
                    messages.Add(id, tag);
                    messageId = id;
                    return(message);
                }
            }
        }
        /// <summary>返回资源</summary>
        /// <param name="message">ref类型的参数,将在函数内部设为null,意味着返回后不能再用。</param>
        /// <param name="messageId">获取资源时得到的那个messageId。如果返回一个不正确的id,将抛出异常。</param>
        public void ReturnResource(ref T message, long messageId)
        {
            if (!messages.ContainsKey(messageId))
            {
                throw new InvalidOperationException("试图归还一个非法的资源。");
            }

            T toDispose = null;

            lock (key2)
            {
                ResourceWatcher <T> tag = messages[messageId];

                tag.InUse = false;

                //当前的id将作废,不能再用
                messages.Remove(messageId);

                //将当前的message置空,不能再用
                message = null;

                //达到上限,将释放资源
                if (messages.Keys.Count >= maxResource)
                {
                    toDispose = message;
                }
                else
                {
                    messages.Add(NewResourceId(), tag);
                }
            }

            if (toDispose != null)
            {
                toDispose.Dispose();
            }
        }