限時等待某一任務完成示例

<pre name="code" class="csharp">        /// <summary>
        /// 獲取客戶端 1.5s 超時
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private IRedisClient GetClientByTimeOut(int index, bool throwException = false)
        {
            if (_redisClients == null || index < 0 || index >= _redisClients.Length)
            {
                return null;
            }

            var cm = _redisClients[index];
            if (cm == null)
            {
                return null;
            }

            int timeout = 1500;//超時ms            
            var t = System.Threading.Tasks.Task.Factory.StartNew((c) =>
            {
                var prcm=((PooledRedisClientManager)c);                
                var cc= prcm.GetClient();
                return cc;
            }, cm);
            bool right = t.Wait(timeout);
            if (right) return t.Result;

            if (throwException)
            {
                string info = string.Format("無法獲取第{0}個Redis客戶端,可能該Redis實例已掛掉。", index);
                throw new Exception(info);
            }

            //logger.Info(info);
            return null;
        }



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章