Exemplo n.º 1
0
 /// <summary>
 /// Creates a new instance of CachedResult.
 /// </summary>
 /// <param name="path">The path to the cached file.</param>
 /// <param name="updated">If the file was updated as a result of this request, true; otherwise, false.</param>
 /// <param name="state">The state of the cache for this file.</param>
 /// <param name="cachedUntil">The time the cache expires.</param>
 /// <param name="ex">The exception that prevented the file from being updated, if any.</param>
 public CacheResult(string path, bool updated, CacheState state, DateTime cachedUntil, Exception ex)
 {
     m_path = path;
     m_updated = updated;
     m_state = state;
     m_cachedUntil = cachedUntil;
     m_ex = ex;
 }
			/// <summary>
			/// Initializes a new instance of the <see cref="CacheItem"/> class.
			/// </summary>
			/// <param name="extension">The file extension.</param>
			/// <param name="smallIcon">The small shell icon.</param>
			/// <param name="largeIcon">The large shell icon.</param>
			/// <param name="filetype">The shell file type.</param>
			/// <param name="state">The cache state of the item.</param>
			public CacheItem(string extension, Image smallIcon, Image largeIcon, string filetype, CacheState state)
			{
				Extension = extension;
				SmallIcon = smallIcon;
				LargeIcon = largeIcon;
				FileType = filetype;
				State = state;
				disposed = false;
			}
 /// <summary>
 /// Initializes a new instance of the CacheItem class
 /// for use with a virtual item.
 /// </summary>
 /// <param name="guid">The guid of the ImageListViewItem.</param>
 /// <param name="key">The public key for the virtual item.</param>
 /// <param name="size">The size of the requested thumbnail.</param>
 /// <param name="image">The thumbnail image.</param>
 /// <param name="state">The cache state of the item.</param>
 public CacheItem(Guid guid, object key, Size size, Image image, CacheState state)
     : this(guid, key, size, image, state, UseEmbeddedThumbnails.Auto)
 {
     ;
 }
Exemplo n.º 4
0
 /// <summary>
 /// Creates a new <see cref="WebApiResponse" /> with a string as backing content.
 /// </summary>
 /// <param name="content">The content.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="cacheState">The cache state.</param>
 /// <param name="responseHeaders">The response headers.</param>
 /// <exception cref="ArgumentNullException"><paramref name="content"/> is <see langword="null"/>.</exception>
 public WebApiResponse(string content, HttpStatusCode?statusCode, CacheState cacheState, IDictionary <string, string>?responseHeaders)
     : base(content, statusCode, cacheState, responseHeaders)
 {
 }
Exemplo n.º 5
0
        /// <summary>
        /// Inserts the given item without raising a selection changed event.
        /// </summary>
        /// <param name="index">Insertion index. If index is -1 the item is added to the end of the list.</param>
        /// <param name="item">The <see cref="ImageListViewItem"/> to add.</param>
        /// <param name="adaptor">The adaptor associated with this item.</param>
        /// <returns>true if the item was added; otherwise false.</returns>
        internal bool InsertInternal(int index, ImageListViewItem item, ImageListViewItemAdaptor adaptor)
        {
            if (mImageListView == null)
            {
                return(false);
            }

            // Check if the file already exists
            if (!string.IsNullOrEmpty(item.FileName) && !mImageListView.AllowDuplicateFileNames)
            {
                if (mItems.Exists(a => string.Compare(a.FileName, item.FileName, StringComparison.OrdinalIgnoreCase) == 0))
                {
                    return(false);
                }
            }
            item.owner    = this;
            item.mAdaptor = adaptor;
            if (index == -1)
            {
                item.mIndex = mItems.Count;
                mItems.Add(item);
            }
            else
            {
                item.mIndex = index;
                for (int i = index; i < mItems.Count; i++)
                {
                    mItems[i].mIndex++;
                }
                mItems.Insert(index, item);
            }
            lookUp.Add(item.Guid, item);
            collectionModified = true;

            item.mImageListView = mImageListView;

            // Create sub item texts for custom columns
            foreach (ImageListViewColumnHeader header in mImageListView.Columns)
            {
                if (header.Type == ColumnType.Custom)
                {
                    item.AddSubItemText(header.Guid);
                }
            }

            // Add current thumbnail to cache
            if (item.clonedThumbnail != null)
            {
                mImageListView.thumbnailCache.Add(item.Guid, item.Adaptor, item.VirtualItemKey, mImageListView.ThumbnailSize,
                                                  item.clonedThumbnail, mImageListView.UseEmbeddedThumbnails, mImageListView.AutoRotateThumbnails,
                                                  (mImageListView.UseWIC == UseWIC.Auto || mImageListView.UseWIC == UseWIC.ThumbnailsOnly));
                item.clonedThumbnail = null;
            }

            // Add to thumbnail cache
            if (mImageListView.CacheMode == CacheMode.Continuous)
            {
                mImageListView.thumbnailCache.Add(item.Guid, item.Adaptor, item.VirtualItemKey,
                                                  mImageListView.ThumbnailSize, mImageListView.UseEmbeddedThumbnails, mImageListView.AutoRotateThumbnails,
                                                  (mImageListView.UseWIC == UseWIC.Auto || mImageListView.UseWIC == UseWIC.ThumbnailsOnly));
            }

            // Add to details cache
            mImageListView.metadataCache.Add(item.Guid, item.Adaptor, item.VirtualItemKey,
                                             (mImageListView.UseWIC == UseWIC.Auto || mImageListView.UseWIC == UseWIC.DetailsOnly));

            // Add to shell info cache
            string extension = item.extension;

            if (!string.IsNullOrEmpty(extension))
            {
                CacheState state = mImageListView.shellInfoCache.GetCacheState(extension);
                if (state == CacheState.Error && mImageListView.RetryOnError == true)
                {
                    mImageListView.shellInfoCache.Remove(extension);
                    mImageListView.shellInfoCache.Add(extension);
                }
                else if (state == CacheState.Unknown)
                {
                    mImageListView.shellInfoCache.Add(extension);
                }
            }

            // Update groups
            if (mImageListView.GroupsVisible)
            {
                AddRemoveGroupItem(item.Index, true);
            }

            // Raise the add event
            mImageListView.OnItemCollectionChanged(new ItemCollectionChangedEventArgs(CollectionChangeAction.Add, item));

            return(true);
        }
			/// <summary>
			/// Initializes a new instance of the <see cref="CacheItem"/> class
			/// for use with a virtual item.
			/// </summary>
			/// <param name="guid">The guid of the ImageListViewItem.</param>
			/// <param name="size">The size of the requested thumbnail.</param>
			/// <param name="image">The thumbnail image.</param>
			/// <param name="rating">The rating of the item.</param>
			/// <param name="state">The cache state of the item.</param>
			/// <param name="useEmbeddedThumbnails">UseEmbeddedThumbnails property of the owner control.</param>
			/// <param name="autoRotate">AutoRotate property of the owner control.</param>
			/// <param name="useWIC">Whether to use WIC.</param>
			public CacheItem(Guid guid, Size size, Image image, ushort rating, CacheState state, UseEmbeddedThumbnails useEmbeddedThumbnails, bool autoRotate, bool useWIC)
			{
				Guid = guid;
				Size = size;
				Image = image;
				Rating = rating;
				State = state;
				UseEmbeddedThumbnails = useEmbeddedThumbnails;
				AutoRotate = autoRotate;
				UseWIC = useWIC;
				disposed = false;
			}
Exemplo n.º 7
0
        private int AcquireModify(Acquire rpc)
        {
            CacheHolder sender = (CacheHolder)rpc.Sender.UserState;

            rpc.Result = rpc.Argument;

            while (true)
            {
                CacheState cs = global.GetOrAdd(rpc.Argument.GlobalTableKey, (tabkeKeyNotUsed) => new CacheState());
                lock (cs)
                {
                    if (cs.AcquireStatePending == StateRemoved)
                    {
                        continue;
                    }

                    while (cs.AcquireStatePending != StateInvalid)
                    {
                        switch (cs.AcquireStatePending)
                        {
                        case StateShare:
                            if (cs.Modify == sender)
                            {
                                logger.Debug("1 {0} {1} {2}", sender, rpc.Argument.State, cs);
                                rpc.Result.State = StateInvalid;
                                rpc.SendResultCode(AcquireModifyDeadLockFound);
                                return(0);
                            }
                            break;

                        case StateModify:
                            if (cs.Modify == sender || cs.Share.Contains(sender))
                            {
                                logger.Debug("2 {0} {1} {2}", sender, rpc.Argument.State, cs);
                                rpc.Result.State = StateInvalid;
                                rpc.SendResultCode(AcquireModifyDeadLockFound);
                                return(0);
                            }
                            break;
                        }
                        logger.Debug("3 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        Monitor.Wait(cs);
                    }
                    cs.AcquireStatePending = StateModify;

                    if (cs.Modify != null)
                    {
                        if (cs.Modify == sender)
                        {
                            logger.Debug("4 {0} {1} {2}", sender, rpc.Argument.State, cs);
                            // 已经是Modify又申请,可能是sender异常关闭,又重启连上。
                            // 更新一下。应该是不需要的。
                            sender.Acquired[rpc.Argument.GlobalTableKey] = StateModify;
                            rpc.SendResultCode(AcquireModifyAlreadyIsModify);
                            cs.AcquireStatePending = StateInvalid;
                            return(0);
                        }

                        int stateReduceResult = StateReduceException;
                        Zeze.Util.Task.Run(
                            () =>
                        {
                            stateReduceResult = cs.Modify.Reduce(rpc.Argument.GlobalTableKey, StateInvalid);
                            lock (cs)
                            {
                                Monitor.PulseAll(cs);
                            }
                        },
                            "GlobalCacheManager.AcquireModify.Reduce");
                        logger.Debug("5 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        Monitor.Wait(cs);

                        switch (stateReduceResult)
                        {
                        case StateInvalid:
                            cs.Modify.Acquired.TryRemove(rpc.Argument.GlobalTableKey, out var _);
                            break;     // reduce success

                        default:
                            // case StateReduceRpcTimeout:
                            // case StateReduceException:
                            // case StateReduceNetError:
                            cs.AcquireStatePending = StateInvalid;
                            Monitor.Pulse(cs);

                            logger.Error("XXX 9 {0} {1} {2}", sender, rpc.Argument.State, cs);
                            rpc.Result.State = StateInvalid;
                            rpc.SendResultCode(AcquireModifyFaild);
                            return(0);
                        }

                        cs.Modify = sender;
                        sender.Acquired[rpc.Argument.GlobalTableKey] = StateModify;
                        cs.AcquireStatePending = StateInvalid;
                        Monitor.Pulse(cs);

                        logger.Debug("6 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        rpc.SendResult();
                        return(0);
                    }

                    List <Util.KV <CacheHolder, Reduce> > reducePending
                        = new List <Util.KV <CacheHolder, Reduce> >();
                    HashSet <CacheHolder> reduceSuccessed = new HashSet <CacheHolder>();
                    bool senderIsShare = false;
                    // 先把降级请求全部发送给出去。
                    foreach (CacheHolder c in cs.Share)
                    {
                        if (c == sender)
                        {
                            senderIsShare = true;
                            reduceSuccessed.Add(sender);
                            continue;
                        }
                        Reduce reduce = c.ReduceWaitLater(rpc.Argument.GlobalTableKey, StateInvalid);
                        if (null != reduce)
                        {
                            reducePending.Add(Util.KV.Create(c, reduce));
                        }
                        else
                        {
                            // 网络错误不再认为成功。整个降级失败,要中断降级。
                            // 已经发出去的降级请求要等待并处理结果。后面处理。
                            break;
                        }
                    }

                    Zeze.Util.Task.Run(
                        () =>
                    {
                        // 一个个等待是否成功。WaitAll 碰到错误不知道怎么处理的,
                        // 应该也会等待所有任务结束(包括错误)。
                        foreach (var reduce in reducePending)
                        {
                            try
                            {
                                reduce.Value.Future.Task.Wait();
                                if (reduce.Value.Result.State == StateInvalid)
                                {
                                    // 后面还有个成功的处理循环,但是那里可能包含sender,
                                    // 在这里更新吧。
                                    reduce.Key.Acquired.TryRemove(rpc.Argument.GlobalTableKey, out var _);
                                    reduceSuccessed.Add(reduce.Key);
                                }
                                else
                                {
                                    reduce.Key.SetError();
                                }
                            }
                            catch (Exception ex)
                            {
                                reduce.Key.SetError();
                                // 等待失败不再看作成功。
                                logger.Error(ex, "Reduce {0} {1} {2} {3}", sender, rpc.Argument.State, cs, reduce.Value.Argument);
                            }
                        }
                        lock (cs)
                        {
                            // 需要唤醒等待任务结束的,但没法指定,只能全部唤醒。
                            Monitor.PulseAll(cs);
                        }
                    },
                        "GlobalCacheManager.AcquireModify.WaitReduce");
                    logger.Debug("7 {0} {1} {2}", sender, rpc.Argument.State, cs);
                    Monitor.Wait(cs);

                    // 移除成功的。
                    foreach (CacheHolder successed in reduceSuccessed)
                    {
                        cs.Share.Remove(successed);
                    }

                    // 如果前面降级发生中断(break),这里就不会为0。
                    if (cs.Share.Count == 0)
                    {
                        cs.Modify = sender;
                        sender.Acquired[rpc.Argument.GlobalTableKey] = StateModify;
                        cs.AcquireStatePending = StateInvalid;
                        Monitor.Pulse(cs); // Pending 结束,唤醒一个进来就可以了。

                        logger.Debug("8 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        rpc.SendResult();
                    }
                    else
                    {
                        // senderIsShare 在失败的时候,Acquired 没有变化,不需要更新。
                        // 失败了,要把原来是share的sender恢复。先这样吧。
                        if (senderIsShare)
                        {
                            cs.Share.Add(sender);
                        }

                        cs.AcquireStatePending = StateInvalid;
                        Monitor.Pulse(cs); // Pending 结束,唤醒一个进来就可以了。

                        logger.Error("XXX 10 {0} {1} {2}", sender, rpc.Argument.State, cs);

                        rpc.Result.State = StateInvalid;
                        rpc.SendResultCode(AcquireModifyFaild);
                    }
                    // 很好,网络失败不再看成成功,发现除了加break,
                    // 其他处理已经能包容这个改动,都不用动。
                    return(0);
                }
            }
        }
Exemplo n.º 8
0
        private void RebuildStatusCacheIfNeeded(bool ignoreBackoff)
        {
            bool     needToRebuild = false;
            DateTime now;

            lock (this.cacheFileLock)
            {
                CacheState cacheState = this.cacheState;
                now = DateTime.UtcNow;

                if (cacheState == CacheState.Clean)
                {
                    this.context.Tracer.RelatedInfo("GitStatusCache.RebuildStatusCacheIfNeeded: Status Cache up-to-date.");
                }
                else if (!this.TryDeleteStatusCacheFile())
                {
                    // The cache is dirty, but we failed to delete the previous on disk cache.
                    // Do not rebuild the cache this time. Wait for the next invalidation
                    // to cause the thread to run again, or the on-disk cache will be deleted
                    // if a status command is run.
                }
                else if (!ignoreBackoff &&
                         (now - this.lastInvalidationTime) < this.backoffTime)
                {
                    // The approriate backoff time has not elapsed yet,
                    // If this is the 1st time we are delaying the background
                    // status scan (indicated by the initialDelayTime being set to
                    // DateTime.MinValue), mark the current time. We can then track
                    // how long the scan was delayed for.
                    if (this.initialDelayTime == DateTime.MinValue)
                    {
                        this.initialDelayTime = now;
                    }

                    // Signal the background thread to run again, so it
                    // can check if the backoff time has elapsed and it should
                    // rebuild the status cache.
                    this.wakeUpThread.Set();
                }
                else
                {
                    // The cache is dirty, and we succeeded in deleting the previous on disk cache and the minimum
                    // backoff time has passed, so now we can rebuild the status cache.
                    needToRebuild = true;
                }
            }

            if (needToRebuild)
            {
                if (this.initialDelayTime > DateTime.MinValue)
                {
                    this.context.Tracer.RelatedInfo("GitStatusCache.RebuildStatusCacheIfNeeded: Generating new Status Cache... Status scan was delayed for: {0:0.##}s", (now - this.initialDelayTime).TotalSeconds);
                }
                else
                {
                    this.context.Tracer.RelatedInfo("GitStatusCache.RebuildStatusCacheIfNeeded: Generating new Status Cache...");
                }

                this.statistics.RecordBackgroundStatusScanRun();

                bool rebuildStatusCacheSucceeded = this.TryRebuildStatusCache();

                this.context.Tracer.RelatedInfo("GitStatusCache.RebuildStatusCacheIfNeeded: Done generating status. Cache is now: {0}", this.cacheState);

                this.initialDelayTime = DateTime.MinValue;
            }
        }
Exemplo n.º 9
0
 /// <summary>
 /// Creates a new <see cref="HttpResponseStream" />.
 /// </summary>
 /// <param name="contentStream">The content stream.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="cacheState">The cache state.</param>
 /// <param name="requestHeaders">The original headers that were used in the web request.</param>
 /// <param name="responseHeaders">The response headers.</param>
 /// <exception cref="ArgumentNullException"><paramref name="contentStream"/> is <see langword="null"/>.</exception>
 public HttpResponseStream(Stream contentStream, HttpStatusCode?statusCode, CacheState cacheState,
                           IEnumerable <KeyValuePair <string, string> >?requestHeaders, IEnumerable <KeyValuePair <string, string> >?responseHeaders) :
     this(contentStream, statusCode, cacheState, requestHeaders?.ShallowCopy(), responseHeaders?.ShallowCopy())
 {
 }
Exemplo n.º 10
0
      private CacheState CompareState( CacheState a, CacheState b )
      {
        if ( a == CacheState.Invalid || b == CacheState.Invalid )               //任何一个状态无效则无效
          return CacheState.Invalid;

        else if ( a == CacheState.NearInvalid || b == CacheState.NearInvalid )  //在没有无效状态的前提下,有接近无效状态则接近无效
          return CacheState.NearInvalid;

        else if ( a == CacheState.Valid && b == CacheState.Valid )              //只有两个状态都有效的时候才是有效的
          return CacheState.Valid;

        else                                                                                        //无法识别的状态都是无效
          return CacheState.Invalid;


      }
Exemplo n.º 11
0
 public CacheUsing removeCache()
 {
     this.cacheController = CacheState.Remove;
     return(this);
 }
Exemplo n.º 12
0
 /// <summary>
 /// Creates a new <see cref="HttpResponseStream" />.
 /// </summary>
 /// <param name="contentStream">The content stream.</param>
 /// <param name="cacheState">The cache state.</param>
 /// <exception cref="ArgumentNullException"><paramref name="contentStream"/> is <see langword="null"/>.</exception>
 public HttpResponseStream(Stream contentStream, CacheState cacheState) : this(contentStream, null, cacheState, null, null)
 {
 }
Exemplo n.º 13
0
 public CacheUsing refurbishCache(bool isRefubish)
 {
     this.cacheController = (isRefubish ? CacheState.Refurbish : CacheState.Using);
     return(this);
 }
Exemplo n.º 14
0
 public CacheUsing refurbishCache()
 {
     this.cacheController = CacheState.Refurbish;
     return(this);
 }
Exemplo n.º 15
0
        private Object cacheCondition; //Fun1<Boolean,T>

        //#endregion

        //#region ICacheUsing<Q> 成员

        public CacheUsing usingCache(bool isCache)
        {
            this.cacheController = (isCache ? CacheState.Using : CacheState.NonUsing);
            return(this);
        }
 /// <summary>
 /// Initializes a new instance of the CacheItem class.
 /// </summary>
 /// <param name="guid">The guid of the ImageListViewItem.</param>
 /// <param name="filename">The file system path to the image file.</param>
 /// <param name="size">The size of the requested thumbnail.</param>
 /// <param name="image">The thumbnail image.</param>
 /// <param name="state">The cache state of the item.</param>
 /// <param name="useEmbeddedThumbnails">UseEmbeddedThumbnails property of the owner control.</param>
 public CacheItem(Guid guid, string filename, Size size, Image image, CacheState state, UseEmbeddedThumbnails useEmbeddedThumbnails)
 {
     mGuid = guid;
     mFileName = filename;
     mSize = size;
     mImage = image;
     mState = state;
     mUseEmbeddedThumbnails = useEmbeddedThumbnails;
     mIsVirtualItem = false;
     disposed = false;
 }
Exemplo n.º 17
0
 public DocumentCache(CacheState state, XElement document)
 {
     State    = state;
     Document = document;
 }
Exemplo n.º 18
0
      public override CacheState GetCacheState()
      {

        if ( _state == CacheState.Invalid )
          return CacheState.Invalid;

        foreach ( var item in _items )
        {
          _state = CompareState( _state, item.GetCacheState() );
          if ( _state == CacheState.Invalid )
            return CacheState.Invalid;
        }


        return _state;
      }
Exemplo n.º 19
0
        /// <summary>
        /// Gets an image from the cache manager.
        /// If the thumbnail image is not cached, it will be
        /// added to the cache queue and DefaultImage of the owner image list view will
        /// be returned. If the thumbnail could not be cached ErrorImage of the owner
        /// image list view will be returned.
        /// </summary>
        /// <param name="imageType">Type of cached image to return.</param>
        /// <returns>Requested thumbnail or icon.</returns>
        public Image GetCachedImage(CachedImageType imageType)
        {
            if (mImageListView == null)
            {
                throw new InvalidOperationException("Owner control is null.");
            }

            string iconPath = null;

            if (imageType == CachedImageType.SmallIcon || imageType == CachedImageType.LargeIcon)
            {
                if (string.IsNullOrEmpty(iconPath))
                {
                    return(mImageListView.DefaultImage);
                }

                CacheState state = mImageListView.shellInfoCache.GetCacheState(iconPath);
                if (state == CacheState.Cached)
                {
                    if (imageType == CachedImageType.SmallIcon)
                    {
                        return(mImageListView.shellInfoCache.GetSmallIcon(iconPath));
                    }
                    else
                    {
                        return(mImageListView.shellInfoCache.GetLargeIcon(iconPath));
                    }
                }
                else if (state == CacheState.Error)
                {
                    if (mImageListView.RetryOnError)
                    {
                        mImageListView.shellInfoCache.Remove(iconPath);
                        mImageListView.shellInfoCache.Add(iconPath);
                    }
                    return(mImageListView.ErrorImage);
                }
                else
                {
                    mImageListView.shellInfoCache.Add(iconPath);
                    return(mImageListView.DefaultImage);
                }
            }
            else
            {
                Image      img   = null;
                CacheState state = ThumbnailCacheState;

                if (state == CacheState.Error)
                {
                    if (mImageListView.ShellIconFallback && !string.IsNullOrEmpty(iconPath))
                    {
                        CacheState iconstate = mImageListView.shellInfoCache.GetCacheState(iconPath);
                        if (iconstate == CacheState.Cached)
                        {
                            if (mImageListView.ThumbnailSize.Width > 32 && mImageListView.ThumbnailSize.Height > 32)
                            {
                                img = mImageListView.shellInfoCache.GetLargeIcon(iconPath);
                            }
                            else
                            {
                                img = mImageListView.shellInfoCache.GetSmallIcon(iconPath);
                            }
                        }
                        else if (iconstate == CacheState.Error)
                        {
                            if (mImageListView.RetryOnError)
                            {
                                mImageListView.shellInfoCache.Remove(iconPath);
                                mImageListView.shellInfoCache.Add(iconPath);
                            }
                        }
                        else
                        {
                            mImageListView.shellInfoCache.Add(iconPath);
                        }
                    }

                    if (img == null)
                    {
                        img = mImageListView.ErrorImage;
                    }
                    return(img);
                }

                img = mImageListView.thumbnailCache.GetImage(Guid, mAdaptor, mVirtualItemKey, mImageListView.ThumbnailSize, mImageListView.UseEmbeddedThumbnails,
                                                             mImageListView.AutoRotateThumbnails, mImageListView.UseWIC == UseWIC.Auto || mImageListView.UseWIC == UseWIC.ThumbnailsOnly, false);

                if (state == CacheState.Cached)
                {
                    return(img);
                }

                mImageListView.thumbnailCache.Add(Guid, mAdaptor, mVirtualItemKey, mImageListView.ThumbnailSize,
                                                  mImageListView.UseEmbeddedThumbnails, mImageListView.AutoRotateThumbnails,
                                                  (mImageListView.UseWIC == UseWIC.Auto || mImageListView.UseWIC == UseWIC.ThumbnailsOnly));

                if (img == null && string.IsNullOrEmpty(iconPath))
                {
                    return(mImageListView.DefaultImage);
                }

                if (img == null && mImageListView.ShellIconFallback && mImageListView.ThumbnailSize.Width > 16 && mImageListView.ThumbnailSize.Height > 16)
                {
                    img = mImageListView.shellInfoCache.GetLargeIcon(iconPath);
                }
                if (img == null && mImageListView.ShellIconFallback)
                {
                    img = mImageListView.shellInfoCache.GetSmallIcon(iconPath);
                }
                if (img == null)
                {
                    img = mImageListView.DefaultImage;
                }

                return(img);
            }
        }
Exemplo n.º 20
0
        private int AcquireShare(Acquire rpc)
        {
            CacheHolder sender = (CacheHolder)rpc.Sender.UserState;

            rpc.Result = rpc.Argument;
            while (true)
            {
                CacheState cs = global.GetOrAdd(rpc.Argument.GlobalTableKey,
                                                (tabkeKeyNotUsed) => new CacheState());
                lock (cs)
                {
                    if (cs.AcquireStatePending == StateRemoved)
                    {
                        continue;
                    }

                    while (cs.AcquireStatePending != StateInvalid)
                    {
                        switch (cs.AcquireStatePending)
                        {
                        case StateShare:
                            if (cs.Modify == sender)
                            {
                                logger.Debug("1 {0} {1} {2}", sender, rpc.Argument.State, cs);
                                rpc.Result.State = StateInvalid;
                                rpc.SendResultCode(AcquireShareDeadLockFound);
                                return(0);
                            }
                            break;

                        case StateModify:
                            if (cs.Modify == sender || cs.Share.Contains(sender))
                            {
                                logger.Debug("2 {0} {1} {2}", sender, rpc.Argument.State, cs);
                                rpc.Result.State = StateInvalid;
                                rpc.SendResultCode(AcquireShareDeadLockFound);
                                return(0);
                            }
                            break;
                        }
                        logger.Debug("3 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        Monitor.Wait(cs);
                    }
                    cs.AcquireStatePending = StateShare;

                    if (cs.Modify != null)
                    {
                        if (cs.Modify == sender)
                        {
                            cs.AcquireStatePending = StateInvalid;
                            logger.Debug("4 {0} {1} {2}", sender, rpc.Argument.State, cs);
                            rpc.Result.State = StateModify;
                            // 已经是Modify又申请,可能是sender异常关闭,
                            // 又重启连上。更新一下。应该是不需要的。
                            sender.Acquired[rpc.Argument.GlobalTableKey] = StateModify;
                            rpc.SendResultCode(AcquireShareAlreadyIsModify);
                            return(0);
                        }

                        int stateReduceResult = StateReduceException;
                        Zeze.Util.Task.Run(
                            () =>
                        {
                            stateReduceResult = cs.Modify.Reduce(rpc.Argument.GlobalTableKey, StateShare);

                            lock (cs)
                            {
                                Monitor.PulseAll(cs);
                            }
                        },
                            "GlobalCacheManager.AcquireShare.Reduce");
                        logger.Debug("5 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        Monitor.Wait(cs);

                        switch (stateReduceResult)
                        {
                        case StateShare:
                            cs.Modify.Acquired[rpc.Argument.GlobalTableKey] = StateShare;
                            cs.Share.Add(cs.Modify);
                            // 降级成功,有可能降到 Invalid,此时就不需要加入 Share 了。
                            break;

                        default:
                            // 包含协议返回错误的值的情况。
                            // case StateReduceRpcTimeout:
                            // case StateReduceException:
                            // case StateReduceNetError:
                            cs.AcquireStatePending = StateInvalid;
                            Monitor.Pulse(cs);

                            logger.Error("XXX 8 {0} {1} {2}", sender, rpc.Argument.State, cs);
                            rpc.Result.State = StateInvalid;
                            rpc.SendResultCode(AcquireShareFaild);
                            return(0);
                        }

                        cs.Modify = null;
                        sender.Acquired[rpc.Argument.GlobalTableKey] = StateShare;
                        cs.Share.Add(sender);
                        cs.AcquireStatePending = StateInvalid;
                        Monitor.Pulse(cs);
                        logger.Debug("6 {0} {1} {2}", sender, rpc.Argument.State, cs);
                        rpc.SendResult();
                        return(0);
                    }

                    sender.Acquired[rpc.Argument.GlobalTableKey] = StateShare;
                    cs.Share.Add(sender);
                    cs.AcquireStatePending = StateInvalid;
                    logger.Debug("7 {0} {1} {2}", sender, rpc.Argument.State, cs);
                    rpc.SendResult();
                    return(0);
                }
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Invalidate the status cache. Does not cause the cache to refresh
 /// If caller also wants to signal the refresh, they must call
 /// <see cref="RefreshAsynchronously" or cref="RefreshAndWait"/>.
 /// </summary>
 public virtual void Invalidate()
 {
     this.lastInvalidationTime = DateTime.UtcNow;
     this.cacheState           = CacheState.Dirty;
 }
Exemplo n.º 22
0
        public void PassesCacheState(CacheState cacheState)
        {
            var response = new HttpResponseInfo(HttpStatusCode.OK, cacheState, null);

            response.CacheState.Should().Be(cacheState);
        }
Exemplo n.º 23
0
 /// <summary>
 /// Creates a new instance of CachedResult.
 /// </summary>
 /// <param name="path">The path to the cached file.</param>
 /// <param name="updated">If the file was updated as a result of this request, true; otherwise, false.</param>
 /// <param name="state">The state of the cache for this file.</param>
 /// <param name="cachedUntil">The time the cache expires.</param>
 public CacheResult(string path, bool updated, CacheState state, DateTime cachedUntil) : this(path, updated, state, cachedUntil, null) { }
Exemplo n.º 24
0
        /// <summary>
        /// Rebuild the status cache. This will run the background status to
        /// generate status results, and update the serialized status cache
        /// file.
        /// </summary>
        private bool TryRebuildStatusCache()
        {
            this.context.FileSystem.CreateDirectory(this.context.Enlistment.GitStatusCacheFolder);

            // The status cache is regenerated on mount. This means that even if the write to temp file
            // and rename operation doesn't complete (due to a system crash), and there is a torn write,
            // GVFS is still protected because a new status cache file will be generated on mount.
            string tmpStatusFilePath = Path.Combine(this.context.Enlistment.GitStatusCacheFolder, Path.GetRandomFileName() + "_status.tmp");

            GitProcess.Result statusResult = null;

            // Do not modify this block unless you completely understand the comments and code within
            {
                // We MUST set the state to Rebuilding _immediately before_ we call the `git status` command. That allows us to
                // check afterwards if anything happened during the status command that should invalidate the cache, and we
                // can discard its results if that happens.
                this.cacheState = CacheState.Rebuilding;

                GitProcess git = this.context.Enlistment.CreateGitProcess();
                statusResult = git.SerializeStatus(
                    allowObjectDownloads: true,
                    serializePath: tmpStatusFilePath);
            }

            bool rebuildSucceeded = false;

            if (!statusResult.HasErrors)
            {
                lock (this.cacheFileLock)
                {
                    // Only update the cache if our state is still Rebuilding. Otherwise, this indicates that another call
                    // to Invalidate came in, and moved the state back to Dirty.
                    if (this.cacheState == CacheState.Rebuilding)
                    {
                        rebuildSucceeded = this.MoveCacheFileToFinalLocation(tmpStatusFilePath);
                        if (rebuildSucceeded)
                        {
                            // We have to check the state once again, because it could have been invalidated while we were
                            // copying the file in the previous step. Here we do it as a CompareExchange to minimize any further races.
                            if (Interlocked.CompareExchange(ref this.cacheState, CacheState.Clean, CacheState.Rebuilding) != CacheState.Rebuilding)
                            {
                                // We did not succeed in setting the state to Clean. Note that we have already overwritten the on disk cache,
                                // but all users of the cache file first check the cacheState, and since the cacheState is not Clean, no one
                                // should ever read it.

                                rebuildSucceeded = false;
                            }
                        }

                        if (!rebuildSucceeded)
                        {
                            this.cacheState = CacheState.Dirty;
                        }
                    }
                }

                if (!rebuildSucceeded)
                {
                    try
                    {
                        this.context.FileSystem.DeleteFile(tmpStatusFilePath);
                    }
                    catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException)
                    {
                        EventMetadata metadata = new EventMetadata();

                        metadata.Add("Area", EtwArea);
                        metadata.Add("Exception", ex.ToString());

                        this.context.Tracer.RelatedError(
                            metadata,
                            string.Format("GitStatusCache is unable to delete temporary status cache file at {0}.", tmpStatusFilePath));
                    }
                }
            }
            else
            {
                this.statistics.RecordBackgroundStatusScanError();
                this.context.Tracer.RelatedInfo("GitStatusCache.TryRebuildStatusCache: Error generating status: {0}", statusResult.Errors);
            }

            return(rebuildSucceeded);
        }
Exemplo n.º 25
0
 /// <summary>
 /// Creates a new <see cref="WebApiResponse" /> with a string as backing content.
 /// </summary>
 /// <param name="content">The content.</param>
 /// <param name="statusCode">The status code.</param>
 /// <param name="cacheState">The cache state.</param>
 /// <param name="responseHeaders">The response headers.</param>
 /// <exception cref="ArgumentNullException"><paramref name="content"/> is <see langword="null"/>.</exception>
 public WebApiResponse(string content, HttpStatusCode?statusCode, CacheState cacheState, IEnumerable <KeyValuePair <string, string> >?responseHeaders)
     : base(content, statusCode, cacheState, responseHeaders)
 {
 }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheItem"/> class.
 /// </summary>
 /// <param name="extension">The file extension.</param>
 /// <param name="smallIcon">The small shell icon.</param>
 /// <param name="largeIcon">The large shell icon.</param>
 /// <param name="filetype">The shell file type.</param>
 /// <param name="state">The cache state of the item.</param>
 public CacheItem(string extension, Image smallIcon, Image largeIcon, string filetype, CacheState state)
 {
     Extension = extension;
     SmallIcon = smallIcon;
     LargeIcon = largeIcon;
     FileType  = filetype;
     State     = state;
     disposed  = false;
 }
Exemplo n.º 27
0
 public PlcCacheResult(CacheState state, int getpos, int savepos)
 {
     this.state   = state;
     this.savepos = savepos;
     this.getpos  = getpos;
 }
 /// <summary>
 /// Initializes a new instance of the CacheItem class
 /// for use with a virtual item.
 /// </summary>
 /// <param name="guid">The guid of the ImageListViewItem.</param>
 /// <param name="key">The public key for the virtual item.</param>
 /// <param name="size">The size of the requested thumbnail.</param>
 /// <param name="image">The thumbnail image.</param>
 /// <param name="state">The cache state of the item.</param>
 public CacheItem(Guid guid, object key, Size size, Image image, CacheState state)
     : this(guid, key, size, image, state, UseEmbeddedThumbnails.Auto)
 {
     ;
 }
 /// <summary>
 /// Initializes a new instance of the CacheItem class
 /// for use with a virtual item.
 /// </summary>
 /// <param name="guid">The guid of the ImageListViewItem.</param>
 /// <param name="key">The public key for the virtual item.</param>
 /// <param name="size">The size of the requested thumbnail.</param>
 /// <param name="image">The thumbnail image.</param>
 /// <param name="state">The cache state of the item.</param>
 /// <param name="useEmbeddedThumbnails">UseEmbeddedThumbnails property of the owner control.</param>
 public CacheItem(Guid guid, object key, Size size, Image image, CacheState state, UseEmbeddedThumbnails useEmbeddedThumbnails)
 {
     mGuid = guid;
     mVirtualItemKey = key;
     mFileName = string.Empty;
     mSize = size;
     mImage = image;
     mState = state;
     mUseEmbeddedThumbnails = useEmbeddedThumbnails;
     mIsVirtualItem = true;
     disposed = false;
 }
Exemplo n.º 30
0
        public CachedQualityNicoVideoListItemViewModel(NicoVideoCacheRequest req, VideoCacheManager cacheManager)
        {
            _Request = req;
            Quality  = _Request.Quality;

            var firstCacheState = _Request.ToCacheState();

            if (firstCacheState != NicoVideoCacheState.Cached)
            {
                CacheState = Observable.FromEventPattern <VideoCacheStateChangedEventArgs>(
                    (x) => cacheManager.VideoCacheStateChanged += x,
                    (x) => cacheManager.VideoCacheStateChanged -= x
                    )
                             .Where(x => x.EventArgs.Request.RawVideoId == _Request.RawVideoId && x.EventArgs.Request.Quality == _Request.Quality)
                             .Select(x => x.EventArgs.CacheState)
                             .ObserveOnUIDispatcher()
                             .ToReadOnlyReactiveProperty(firstCacheState)
                             .AddTo(_CompositeDisposable);

                CacheState.Subscribe(x =>
                {
                    if (x == NicoVideoCacheState.Downloading)
                    {
                        var _cacheManager = App.Current.Container.Resolve <VideoCacheManager>();

                        float firstProgressParcent = 0.0f;
                        if (_Request is NicoVideoCacheProgress)
                        {
                            var prog = (_Request as NicoVideoCacheProgress).DownloadOperation.Progress;
                            if (prog.TotalBytesToReceive > 0)
                            {
                                firstProgressParcent = (float)Math.Round((prog.BytesReceived / (float)prog.TotalBytesToReceive) * 100, 1);
                            }
                        }
                        ProgressPercent = Observable.FromEventPattern <NicoVideoCacheProgress>(
                            (handler) => _cacheManager.DownloadProgress += handler,
                            (handler) => _cacheManager.DownloadProgress -= handler
                            )
                                          .ObserveOnUIDispatcher()
                                          .Where(y => y.EventArgs.RawVideoId == _Request.RawVideoId && y.EventArgs.Quality == _Request.Quality)
                                          .Select(y =>
                        {
                            var prog = y.EventArgs.DownloadOperation.Progress;
                            if (prog.TotalBytesToReceive > 0)
                            {
                                return((float)Math.Round((prog.BytesReceived / (float)prog.TotalBytesToReceive) * 100, 1));
                            }
                            else
                            {
                                return(0.0f);
                            }
                        })
                                          .ToReactiveProperty(firstProgressParcent);
                        RaisePropertyChanged(nameof(ProgressPercent));
                    }
                    else
                    {
                        ProgressPercent?.Dispose();
                        ProgressPercent = null;
                        RaisePropertyChanged(nameof(ProgressPercent));
                    }
                })
                .AddTo(_CompositeDisposable);

                IsCacheDownloading = CacheState.Select(x => x == NicoVideoCacheState.Downloading)
                                     .ToReadOnlyReactiveProperty()
                                     .AddTo(_CompositeDisposable);
            }
            else
            {
                CacheState         = new ReactiveProperty <NicoVideoCacheState>(NicoVideoCacheState.Cached);
                IsCacheDownloading = new ReactiveProperty <bool>(false);
                ProgressPercent    = new ReactiveProperty <float>(0.0f);
            }

            IsCached = CacheState.Select(x => x == NicoVideoCacheState.Cached)
                       .ToReadOnlyReactivePropertySlim()
                       .AddTo(_CompositeDisposable);
        }
 /// <summary>
 /// Initializes a new instance of the CacheItem class.
 /// </summary>
 /// <param name="guid">The guid of the ImageListViewItem.</param>
 /// <param name="filename">The file system path to the image file.</param>
 /// <param name="size">The size of the requested thumbnail.</param>
 /// <param name="image">The thumbnail image.</param>
 /// <param name="state">The cache state of the item.</param>
 public CacheItem(Guid guid, string filename, Size size, Image image, CacheState state)
     : this(guid, filename, size, image, state, UseEmbeddedThumbnails.Auto)
 {
     ;
 }
 /// <summary>
 /// Initializes a new instance of the CacheItem class.
 /// </summary>
 /// <param name="guid">The guid of the ImageListViewItem.</param>
 /// <param name="filename">The file system path to the image file.</param>
 /// <param name="size">The size of the requested thumbnail.</param>
 /// <param name="image">The thumbnail image.</param>
 /// <param name="state">The cache state of the item.</param>
 public CacheItem(Guid guid, string filename, Size size, Image image, CacheState state)
     : this(guid, filename, size, image, state, UseEmbeddedThumbnails.Auto)
 {
     ;
 }
Exemplo n.º 33
0
 /// <summary>
 /// Creates a new <see cref="WebApiResponse" /> with a string as backing content.
 /// </summary>
 /// <param name="content">The content.</param>
 /// <param name="cacheState">The cache state.</param>
 /// <exception cref="ArgumentNullException"><paramref name="content"/> is <see langword="null"/>.</exception>
 public WebApiResponse(string content, CacheState cacheState) : base(content, null, cacheState, null)
 {
 }