示例#1
0
        public Texture2DArray(GraphicsDevice graphicsDevice, int levels, int width, int height, int layers)
            : base(graphicsDevice)
        {
            ThreadingHelper.BlockOnUIThread(() => {
                texture = GL.GenTexture();

                GL.BindTexture(TextureTarget.Texture2DArray, texture);

                GL.TexStorage3D(TextureTarget3d.Texture2DArray, levels, SizedInternalFormat.Rgba8, width, height, Math.Max(layers, 1));
            });
            Width      = width;
            Height     = height;
            LayerCount = layers;
        }
示例#2
0
        internal void Compile()
        {
            ThreadingHelper.BlockOnUIThread(() => {
                GL.CompileShader(shader);

                int compiled;
                GL.GetShader(shader, ShaderParameter.CompileStatus, out compiled);
                if (compiled != 1)
                {
                    string error = GL.GetShaderInfoLog(shader);
                    throw new Exception(error);
                }
            });
        }
示例#3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogManager"/>.
        /// </summary>
        public LogManager()
        {
            ConfigManager.TryRegisterService(this);

            Sources = new LogSourceList(this)
            {
                Application,
                new UnhandledExceptionSource()
            };

            _flushTimer = ThreadingHelper.Timer(Flush);

            FlushInterval = TimeSpan.FromMilliseconds(500);
        }
示例#4
0
        public void SetData <T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) where T : struct
        {
            ThreadingHelper.BlockOnUIThread(() =>
            {
                //vao.Bind();//TODO: verify
                GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);

                GCHandle buffer = GCHandle.Alloc(data, GCHandleType.Pinned);
                GL.BufferSubData(BufferTarget.ArrayBuffer, new IntPtr(offsetInBytes), new IntPtr(elementCount * vertexStride), buffer.AddrOfPinnedObject() + startIndex * vertexStride);

                buffer.Free();
            });
            GraphicsDevice.CheckError();
        }
示例#5
0
 /// <summary>
 /// To subscribe for news.
 /// </summary>
 public void SubscribeNews()
 {
     _newsTimer = ThreadingHelper.Timer(() =>
     {
         try
         {
             RequestNews();
         }
         catch (Exception ex)
         {
             ex.LogError();
         }
     }).Interval(TimeSpan.Zero, TimeSpan.FromDays(1));
 }
示例#6
0
        private void PreprocessMipMaps()
        {
            bool hwCompressed = Format == TextureContentFormat.DXT1 || Format == TextureContentFormat.DXT3 || Format == TextureContentFormat.DXT5;
            int  width = Width, height = Height;
            int  realCount = 0;

            for (int i = 0; i < (GenerateMipMaps ? 1 : MipMapCount); i++)
            {
                if (hwCompressed)
                {
                    int    dataSize = 0;
                    byte[] data     = null;
                    ThreadingHelper.BlockOnUIThread(() =>
                    {
                        GL.BindTexture(TextureTarget.Texture2D, texture);
                        GL.GetTexLevelParameter(TextureTarget.Texture2D, i, GetTextureParameter.TextureCompressedImageSize, out dataSize);
                        data = new byte[dataSize];
                        GL.GetCompressedTexImage(TextureTarget.Texture2D, i, data);
                    });
                    MipMaps.Add(new TextureContentMipMap(width, height, Format, data));
                }
                else
                {
                    var bmp = new System.Drawing.Bitmap(width, height);

                    var bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                    ThreadingHelper.BlockOnUIThread(() =>
                    {
                        GL.BindTexture(TextureTarget.Texture2D, texture);
                        GL.GetTexImage(TextureTarget.Texture2D, i, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
                    });

                    bmp.UnlockBits(bmpData);

                    MipMaps.Add(new TextureContentMipMap(width, height, Format, bmp));
                }
                width  /= 2;
                height /= 2;
                realCount++;
                if (width == 0 || height == 0)
                {
                    break;
                }
            }
            if (!GenerateMipMaps)
            {
                MipMapCount = realCount;
            }
        }
示例#7
0
        private void BrowsePath(object obj)
        {
            FolderBrowserWindow window = new FolderBrowserWindow();

            if (this.viewModel == null)
            {
                this.viewModel = new FolderBrowserViewModel(this.AdapterBase)
                {
                    Message = "Select the destination folder"
                };
                if (!string.IsNullOrWhiteSpace(this.DestinationPath))
                {
                    //this.viewModel.SelectedPath = this.DestinationPath;
                }
            }

            if (!this.viewModel.RootFolders.Any())
            {
                this.viewModel.LoadRootFolders();
            }

            window.DataContext = this.viewModel;

            if (!string.IsNullOrWhiteSpace(this.DestinationPath))
            {
                ThreadingHelper.StartBackgroundTask(
                    (s, t) =>
                {
                    foreach (FolderViewModel root in this.viewModel.RootFolders)
                    {
                        FolderViewModel folder = this.GetFolderByPath(root,
                                                                      this.DestinationPath.Split(new[] { this.AdapterBase.PathSeparator },
                                                                                                 StringSplitOptions.None).ToList());
                        if (folder != null)
                        {
                            folder.IsExpanded = true;
                            folder.IsSelected = true;
                            break;
                        }
                    }
                });
            }

            bool?dialogResult = window.ShowDialog();

            if (dialogResult == true && this.viewModel.SelectedFolder != null)
            {
                this.DestinationPath = this.viewModel.SelectedFolder.GetPath();
            }
        }
示例#8
0
        private bool WaitExtracted(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            var spinWait  = new SpinWait();
            var spinCount = _spinCount;

            if (IsSet)
            {
                return(true);
            }
            var start = ThreadingHelper.TicksNow();

retry_longTimeout:
            if (IsSet)
            {
                return(true);
            }
            cancellationToken.ThrowIfCancellationRequested();
            GC.KeepAlive(cancellationToken.WaitHandle);
            var elapsed = ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start);

            if (elapsed < millisecondsTimeout)
            {
                if (spinCount > 0)
                {
                    spinCount--;
                    spinWait.SpinOnce();
                    goto retry_longTimeout;
                }
                var handle    = RetriveWaitHandle();
                var remaining = millisecondsTimeout - (int)elapsed;
                if (remaining > 0)
                {
                    var result = WaitHandle.WaitAny
                                 (
                        new[]
                    {
                        handle,
                        cancellationToken.WaitHandle
                    },
                        remaining
                                 );
                    cancellationToken.ThrowIfCancellationRequested();
                    GC.KeepAlive(cancellationToken.WaitHandle);
                    return(result != WaitHandle.WaitTimeout);
                }
            }
            cancellationToken.ThrowIfCancellationRequested();
            GC.KeepAlive(cancellationToken.WaitHandle);
            return(false);
        }
示例#9
0
        async Task Initialize()
        {
            // The services needed by the usage tracker are loaded when they are first needed to
            // improve the startup time of the extension.
            if (!initialized)
            {
                await ThreadingHelper.SwitchToMainThreadAsync();

                client            = gitHubServiceProvider.TryGetService <IMetricsService>();
                connectionManager = gitHubServiceProvider.GetService <IConnectionManager>();
                vsservices        = gitHubServiceProvider.GetService <IVSServices>();
                initialized       = true;
            }
        }
示例#10
0
        protected override async Task InitializeAsync(
            CancellationToken cancellationToken,
            IProgress <ServiceProgressData> progress)
        {
            var menuService    = (IMenuCommandService)(await GetServiceAsync(typeof(IMenuCommandService)));
            var componentModel = (IComponentModel)(await GetServiceAsync(typeof(SComponentModel)));
            var exports        = componentModel.DefaultExportProvider;

            await ThreadingHelper.SwitchToMainThreadAsync();

            menuService.AddCommands(
                exports.GetExportedValue <INextInlineCommentCommand>(),
                exports.GetExportedValue <IPreviousInlineCommentCommand>());
        }
示例#11
0
        private void TryCreateTimer()
        {
            lock (_syncRoot)
            {
                if (_isFlushing || _flushTimer != null)
                {
                    return;
                }

                _flushTimer = ThreadingHelper
                              .Timer(() => CultureInfo.InvariantCulture.DoInCulture(OnFlush))
                              .Interval(_flushInterval);
            }
        }
        async Task Initialize()
        {
            if (storePath == null)
            {
                await ThreadingHelper.SwitchToMainThreadAsync();

                var program = serviceProvider.GetService <IProgram>();

                var localApplicationDataPath = environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

                storePath     = Path.Combine(localApplicationDataPath, program.ApplicationName, StoreFileName);
                userStorePath = Path.Combine(localApplicationDataPath, program.ApplicationName, UserStoreFileName);
            }
        }
        private bool WaitExtracted(int millisecondsTimeout)
        {
            var count = 0;

            if (IsSet)
            {
                return(true);
            }
            var start = ThreadingHelper.TicksNow();

            if (millisecondsTimeout > INT_LongTimeOutHint)
            {
retry_longTimeout:
                if (IsSet)
                {
                    return(true);
                }
                var elapsed = ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start);
                if (elapsed < millisecondsTimeout)
                {
                    if (elapsed < INT_LongTimeOutHint)
                    {
                        ThreadingHelper.SpinOnce(ref count);
                        goto retry_longTimeout;
                    }
                    var handle    = RetriveWaitHandle();
                    var remaining = millisecondsTimeout - (int)elapsed;
                    if (remaining > 0)
                    {
                        return(handle.WaitOne(remaining));
                    }
                }
            }
            else
            {
retry_shortTimeout:
                if (IsSet)
                {
                    return(true);
                }
                var elapsed = ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start);
                if (elapsed < millisecondsTimeout)
                {
                    ThreadingHelper.SpinOnce(ref count);
                    goto retry_shortTimeout;
                }
            }
            return(false);
        }
示例#14
0
        /// <summary>
        /// To start timer of getting from sent <paramref name="connector" /> of real time candles.
        /// </summary>
        /// <typeparam name="TConnector">The type of the connection implementing <see cref="IExternalCandleSource"/>.</typeparam>
        /// <param name="connector">The connection implementing <see cref="IExternalCandleSource"/>.</param>
        /// <param name="registeredSeries">All registered candles series.</param>
        /// <param name="offset">The time shift for the new request to obtain a new candle. It is needed for the server will have time to create data in its candles storage.</param>
        /// <param name="requestNewCandles">The handler getting new candles.</param>
        /// <param name="interval">The interval between data updates.</param>
        /// <returns>Created timer.</returns>
        public static Timer StartRealTime <TConnector>(this TConnector connector, CachedSynchronizedSet <CandleSeries> registeredSeries, TimeSpan offset, Action <CandleSeries, Range <DateTimeOffset> > requestNewCandles, TimeSpan interval)
            where TConnector : class, IConnector, IExternalCandleSource
        {
            if (connector == null)
            {
                throw new ArgumentNullException(nameof(connector));
            }

            if (registeredSeries == null)
            {
                throw new ArgumentNullException(nameof(registeredSeries));
            }

            if (requestNewCandles == null)
            {
                throw new ArgumentNullException(nameof(requestNewCandles));
            }

            return(ThreadingHelper.Timer(() =>
            {
                try
                {
                    if (connector.ConnectionState != ConnectionStates.Connected)
                    {
                        return;
                    }

                    lock (registeredSeries.SyncRoot)
                    {
                        foreach (var series in registeredSeries.Cache)
                        {
                            var tf = (TimeSpan)series.Arg;
                            var time = connector.CurrentTime;
                            var bounds = tf.GetCandleBounds(time, series.Security.Board);

                            var beginTime = (time - bounds.Min) < offset ? (bounds.Min - tf) : bounds.Min;
                            var finishTime = bounds.Max;

                            requestNewCandles(series, new Range <DateTimeOffset>(beginTime, finishTime));
                        }
                    }
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }
            })
                   .Interval(interval));
        }
        async Task RepoChanged(ILocalRepositoryModel repository)
        {
            try
            {
                await ThreadingHelper.SwitchToMainThreadAsync();
                await EnsureLoggedIn(repository);

                if (repository != this.repository)
                {
                    this.repository = repository;
                    CurrentSession  = null;
                    sessions.Clear();
                }

                var modelService = hosts.LookupHost(HostAddress.Create(repository.CloneUrl))?.ModelService;
                var session      = CurrentSession;

                if (modelService != null)
                {
                    var pr = await service.GetPullRequestForCurrentBranch(repository).FirstOrDefaultAsync();

                    if (pr?.Item1 != (CurrentSession?.PullRequest.Base.RepositoryCloneUrl.Owner) &&
                        pr?.Item2 != (CurrentSession?.PullRequest.Number))
                    {
                        var pullRequest = await GetPullRequestForTip(modelService, repository);

                        if (pullRequest != null)
                        {
                            var newSession = await GetSessionInternal(pullRequest);;
                            if (newSession != null)
                            {
                                newSession.IsCheckedOut = true;
                            }
                            session = newSession;
                        }
                    }
                }
                else
                {
                    session = null;
                }

                CurrentSession = session;
            }
            catch
            {
                // TODO: Log
            }
        }
示例#16
0
 private void WaitAntecedent(CancellationToken cancellationToken, int milliseconds, long start)
 {
     if (IsContinuationTask)
     {
         var antecedent = ((IContinuationTask)this).Antecedent;
         if (antecedent != null)
         {
             antecedent.Wait
             (
                 milliseconds - (int)ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start),
                 cancellationToken
             );
         }
     }
 }
示例#17
0
        private void WaitAntecedent(CancellationToken cancellationToken, int milliseconds, long start)
        {
            if (!IsContinuationTask)
            {
                return;
            }

            var antecedent = ((IContinuationTask)this).Antecedent;

            antecedent?.Wait
            (
                milliseconds - (int)ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start),
                cancellationToken
            );
        }
        private ManualResetEvent TryGetWaitHandleExtracted()
        {
            var handle = ThreadingHelper.VolatileRead(ref _handle);

            if (handle != null)
            {
                if (Thread.VolatileRead(ref _requested) == 2)
                {
                    return(handle);
                }
                handle.Close();
            }
            Thread.VolatileWrite(ref _requested, -1);
            throw new ObjectDisposedException(GetType().FullName);
        }
示例#19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CachedBasketMarketDataStorage{T}"/>.
        /// </summary>
        public CachedBasketMarketDataStorage(BasketMarketDataStorage <T> basketStorage)
        {
            if (basketStorage == null)
            {
                throw new ArgumentNullException(nameof(basketStorage));
            }

            _basketStorage     = basketStorage;
            _cancellationToken = new CancellationTokenSource();

            ThreadingHelper
            .Thread(() => CultureInfo.InvariantCulture.DoInCulture(OnLoad))
            .Name("Cached marketdata storage thread.")
            .Launch();
        }
示例#20
0
        /// <summary>
        /// Добавить сообщение в очередь на отправку.
        /// </summary>
        /// <param name="message">Сообщение.</param>
        private void EnqueueMessage(LogMessage message)
        {
            if (message.IsDispose)
            {
                _queue.Close();
                return;
            }

            _queue.Enqueue(Tuple.Create(GetSubject(message), message.Message));

            lock (_queue.SyncRoot)
            {
                if (_isThreadStarted)
                {
                    return;
                }

                _isThreadStarted = true;

                ThreadingHelper.Thread(() =>
                {
                    try
                    {
                        using (var email = CreateClient())
                        {
                            while (true)
                            {
                                Tuple <string, string> m;

                                if (!_queue.TryDequeue(out m))
                                {
                                    break;
                                }

                                email.Send(From, To, m.Item1, m.Item2);
                            }
                        }

                        lock (_queue.SyncRoot)
                            _isThreadStarted = false;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine(ex);
                    }
                }).Name("Email log queue").Launch();
            }
        }
示例#21
0
        private void LookupPanel_OnLookup(Security filter)
        {
            SecuritiesAll.SecurityFilter = filter.Code;

            var downloader = Task as ISecurityDownloader;

            if (downloader == null)
            {
                return;
            }

            BusyIndicator.BusyContent = LocalizedStrings.Str2834;
            BusyIndicator.IsBusy      = true;

            ThreadingHelper
            .Thread(() =>
            {
                var securities = ConfigManager.GetService <IEntityRegistry>().Securities;

                try
                {
                    downloader.Refresh(securities, filter, s => { }, () => _isClosed);
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }

                try
                {
                    securities.DelayAction.WaitFlush();
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }

                try
                {
                    this.GuiAsync(() => BusyIndicator.IsBusy = false);
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }
            })
            .Launch();
        }
示例#22
0
        async Task InitializeMenus()
        {
            var menus = await GetServiceAsync(typeof(IMenuProvider)) as IMenuProvider;

            await ThreadingHelper.SwitchToMainThreadAsync();

            foreach (var menu in menus.Menus)
            {
                serviceProvider.AddCommandHandler(menu.Guid, menu.CmdId, (s, e) => menu.Activate());
            }

            foreach (var menu in menus.DynamicMenus)
            {
                serviceProvider.AddCommandHandler(menu.Guid, menu.CmdId, menu.CanShow, () => menu.Activate());
            }
        }
        public async Task <TwoFactorChallengeResult> HandleTwoFactorException(TwoFactorAuthorizationException exception)
        {
            await ThreadingHelper.SwitchToMainThreadAsync();

            var userError = new TwoFactorRequiredUserError(exception);
            var result    = await twoFactorDialog.Show(userError);

            if (result != null)
            {
                return(result);
            }
            else
            {
                throw exception;
            }
        }
示例#24
0
 internal void FinishThreadAbortedTask(bool exceptionAdded, bool delegateRan)
 {
     if (Interlocked.CompareExchange(ref _threadAbortedmanaged, 1, 0) == 0)
     {
         var exceptionsHolder = ThreadingHelper.VolatileRead(ref _exceptionsHolder);
         if (exceptionsHolder == null)
         {
             return;
         }
         if (exceptionAdded)
         {
             exceptionsHolder.MarkAsHandled(false);
         }
         Finish(delegateRan);
     }
 }
        public int Release(int releaseCount)
        {
            CheckDisposed();
            if (releaseCount < 1)
            {
                throw new ArgumentOutOfRangeException("releaseCount", "releaseCount is less than 1");
            }
            int oldValue;

            if (ThreadingHelper.SpinWaitRelativeExchangeUnlessNegative(ref _count, -releaseCount, out oldValue))
            {
                Awake();
                return(oldValue);
            }
            throw new SemaphoreFullException();
        }
示例#26
0
 public IndexBuffer(GraphicsDevice graphicsDevice, DrawElementsType indexElementSize, int indexCount, BufferUsageHint usage = BufferUsageHint.StaticDraw)
     : base(graphicsDevice)
 {
     this.IndexElementSize = indexElementSize;
     this.IndexCount       = indexCount;
     this.BufferUsage      = usage;
     ThreadingHelper.BlockOnUIThread(() =>
     {
         ibo = GL.GenBuffer();
         GL.BindBuffer(BufferTarget.ElementArrayBuffer, ibo);
         elementSize = (indexElementSize == DrawElementsType.UnsignedByte ? 1 : (indexElementSize == DrawElementsType.UnsignedShort ? 2 : 4));
         GL.BufferData(BufferTarget.ElementArrayBuffer, new IntPtr(indexCount * elementSize), IntPtr.Zero, (OpenTK.Graphics.OpenGL4.BufferUsageHint)BufferUsage);
     });
     GraphicsDevice.CheckError();
     //buffer = new byte[indexCount * (int)IndexElementSize / 8];
 }
示例#27
0
 public void TryEnter(int millisecondsTimeout, ref bool lockTaken)
 {
     if (_disableThreadTracking)
     {
         lockTaken |= ThreadingHelper.SpinWaitSet(ref _isHeld, 1, 0, millisecondsTimeout);
     }
     else
     {
         if (IsHeldByCurrentThread)
         {
             //Throw on recursion
             throw new LockRecursionException();
         }
         lockTaken |= (ThreadingHelper.SpinWaitSet(ref _isHeld, 1, 0, millisecondsTimeout) && ReferenceEquals(Interlocked.CompareExchange(ref _ownerThread, Thread.CurrentThread, null), null));
     }
 }
示例#28
0
 public override void Wait(int milliseconds, CancellationToken cancellationToken)
 {
     if (Interlocked.CompareExchange(ref _status, 1, 0) != 0)
     {
         base.Wait(milliseconds, cancellationToken);
     }
     else
     {
         var start = ThreadingHelper.TicksNow();
         base.Execute();
         milliseconds = milliseconds - (int)ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start);
         if (milliseconds > 0)
         {
             base.Wait(milliseconds, cancellationToken);
         }
     }
 }
示例#29
0
        public void SetData <T>(T[] data) where T : struct
        {
            if (data.Length == 0)
            {
                return;
            }



            ThreadingHelper.BlockOnUIThread(() =>
            {
                Bind();
                GL.BufferSubData <T>(BufferTarget.ElementArrayBuffer, IntPtr.Zero, new IntPtr(data.Length * Marshal.SizeOf(default(T))), data);   //TODO:
            });
            GraphicsDevice.CheckError();
            //Buffer.BlockCopy (data, 0, buffer, 0, data.Length);
        }
示例#30
0
 public override void Wait(int milliseconds)
 {
     if (Interlocked.CompareExchange(ref _status, 1, 0) != 0)
     {
         base.Wait(milliseconds);
     }
     else
     {
         var start = ThreadingHelper.TicksNow();
         base.Initialize();
         milliseconds -= (int)ThreadingHelper.Milliseconds(ThreadingHelper.TicksNow() - start);
         if (milliseconds > 0)
         {
             base.Wait(milliseconds);
         }
     }
 }