System.GC.KeepAlive(object)

Here are the examples of the csharp api System.GC.KeepAlive(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2249 Examples 7

19 View Source File : DdsNative.cs
License : MIT License
Project Creator : 0xC0000054

public static unsafe DdsImage Load(Stream stream)
        {
            StreamIOCallbacks streamIO = new StreamIOCallbacks(stream);
            IOCallbacks callbacks = new IOCallbacks
            {
                Read = streamIO.Read,
                Write = streamIO.Write,
                Seek = streamIO.Seek,
                GetSize = streamIO.GetSize
            };

            int hr;
            DDSLoadInfo info = new DDSLoadInfo();

            if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
            {
                hr = DdsIO_x64.Load(callbacks, ref info);
            }
            else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
            {
                hr = DdsIO_x86.Load(callbacks, ref info);
            }
            else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
            {
                hr = DdsIO_ARM64.Load(callbacks, ref info);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }

            GC.KeepAlive(streamIO);
            GC.KeepAlive(callbacks);

            if (FAILED(hr))
            {
                if (streamIO.CallbackExceptionInfo != null)
                {
                    streamIO.CallbackExceptionInfo.Throw();
                }
                else
                {
                    switch (hr)
                    {
                        case HResult.InvalidData:
                            throw new FormatException("The DDS file is invalid.");
                        case HResult.NotSupported:
                            throw new FormatException("The file is not a supported DDS format.");
                        default:
                            Marshal.ThrowExceptionForHR(hr);
                            break;
                    }
                }
            }

            return new DdsImage(info);
        }

19 View Source File : DdsNative.cs
License : MIT License
Project Creator : 0xC0000054

public static unsafe void Save(
            DDSSaveInfo info,
            TextureCollection textures,
            Stream output,
            DdsProgressCallback progressCallback)
        {
            StreamIOCallbacks streamIO = new StreamIOCallbacks(output);
            IOCallbacks callbacks = new IOCallbacks
            {
                Read = streamIO.Read,
                Write = streamIO.Write,
                Seek = streamIO.Seek,
                GetSize = streamIO.GetSize
            };

            DDSBitmapData[] bitmapData = CreateBitmapDataArray(textures, info.arraySize, info.mipLevels);

            int hr;

            unsafe
            {
                fixed (DDSBitmapData* pBitmapData = bitmapData)
                {
                    if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
                    {
                        hr = DdsIO_x64.Save(info, pBitmapData, (uint)bitmapData.Length, callbacks, progressCallback);
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
                    {
                        hr = DdsIO_x86.Save(info, pBitmapData, (uint)bitmapData.Length, callbacks, progressCallback);
                    }
                    else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
                    {
                        hr = DdsIO_ARM64.Save(info, pBitmapData, (uint)bitmapData.Length, callbacks, progressCallback);
                    }
                    else
                    {
                        throw new PlatformNotSupportedException();
                    }
                }
            }

            GC.KeepAlive(streamIO);
            GC.KeepAlive(callbacks);
            GC.KeepAlive(progressCallback);

            if (FAILED(hr))
            {
                if (streamIO.CallbackExceptionInfo != null)
                {
                    streamIO.CallbackExceptionInfo.Throw();
                }
                else
                {
                    switch (hr)
                    {
                        case HResult.CanceledError:
                            throw new OperationCanceledException();
                        case HResult.UnknownDdsSaveFormat:
                            throw new InvalidOperationException("The DDSFileFormat value does not map to a DXGI format.");
                        default:
                            Marshal.ThrowExceptionForHR(hr);
                            break;
                    }
                }
            }
        }

19 View Source File : AvifNative.cs
License : MIT License
Project Creator : 0xC0000054

public static void CompressAlphaImage(Surface surface,
                                              EncoderOptions options,
                                              AvifProgressCallback avifProgress,
                                              IArrayPoolService arrayPool,
                                              ref uint progressDone,
                                              uint progressTotal,
                                              out CompressedAV1Image alpha)
        {
            BitmapData bitmapData = new BitmapData
            {
                scan0 = surface.Scan0.Pointer,
                width = (uint)surface.Width,
                height = (uint)surface.Height,
                stride = (uint)surface.Stride
            };

            ProgressContext progressContext = new ProgressContext(avifProgress, progressDone, progressTotal);

            using (CompressedAV1DataAllocator allocator = new CompressedAV1DataAllocator(1, arrayPool))
            {
                IntPtr alphaImage;

                CompressedAV1OutputAlloc outputAllocDelegate = new CompressedAV1OutputAlloc(allocator.Allocate);
                EncoderStatus status = EncoderStatus.Ok;

                if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
                {
                    status = AvifNative_64.CompressAlphaImage(ref bitmapData,
                                                              options,
                                                              progressContext,
                                                              outputAllocDelegate,
                                                              out alphaImage);
                }
                else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
                {
                    status = AvifNative_86.CompressAlphaImage(ref bitmapData,
                                                              options,
                                                              progressContext,
                                                              outputAllocDelegate,
                                                              out alphaImage);
                }
                else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
                {
                    status = AvifNative_ARM64.CompressAlphaImage(ref bitmapData,
                                                                 options,
                                                                 progressContext,
                                                                 outputAllocDelegate,
                                                                 out alphaImage);
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }

                GC.KeepAlive(outputAllocDelegate);

                if (status != EncoderStatus.Ok)
                {
                    HandleError(status, allocator.ExceptionInfo);
                }

                alpha = new CompressedAV1Image(allocator.GetCompressedAV1Data(alphaImage), surface.Width, surface.Height, YUVChromaSubsampling.Subsampling400);
            }

            progressDone = progressContext.progressDone;
            GC.KeepAlive(avifProgress);
        }

19 View Source File : AvifNative.cs
License : MIT License
Project Creator : 0xC0000054

public static void CompressColorImage(Surface surface,
                                              EncoderOptions options,
                                              AvifProgressCallback avifProgress,
                                              IArrayPoolService arrayPool,
                                              ref uint progressDone,
                                              uint progressTotal,
                                              CICPColorData colorInfo,
                                              out CompressedAV1Image color)
        {
            BitmapData bitmapData = new BitmapData
            {
                scan0 = surface.Scan0.Pointer,
                width = (uint)surface.Width,
                height = (uint)surface.Height,
                stride = (uint)surface.Stride
            };

            ProgressContext progressContext = new ProgressContext(avifProgress, progressDone, progressTotal);

            using (CompressedAV1DataAllocator allocator = new CompressedAV1DataAllocator(1, arrayPool))
            {
                IntPtr colorImage;

                CompressedAV1OutputAlloc outputAllocDelegate = new CompressedAV1OutputAlloc(allocator.Allocate);
                EncoderStatus status = EncoderStatus.Ok;
                if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
                {
                    status = AvifNative_64.CompressColorImage(ref bitmapData,
                                                              options,
                                                              progressContext,
                                                              ref colorInfo,
                                                              outputAllocDelegate,
                                                              out colorImage);
                }
                else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
                {
                    status = AvifNative_86.CompressColorImage(ref bitmapData,
                                                              options,
                                                              progressContext,
                                                              ref colorInfo,
                                                              outputAllocDelegate,
                                                              out colorImage);
                }
                else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
                {
                    status = AvifNative_ARM64.CompressColorImage(ref bitmapData,
                                                                 options,
                                                                 progressContext,
                                                                 ref colorInfo,
                                                                 outputAllocDelegate,
                                                                 out colorImage);
                }
                else
                {
                    throw new PlatformNotSupportedException();
                }

                GC.KeepAlive(outputAllocDelegate);

                if (status != EncoderStatus.Ok)
                {
                    HandleError(status, allocator.ExceptionInfo);
                }

                color = new CompressedAV1Image(allocator.GetCompressedAV1Data(colorImage), surface.Width, surface.Height, options.yuvFormat);
            }

            progressDone = progressContext.progressDone;
            GC.KeepAlive(avifProgress);
        }

19 View Source File : VistaFileSaveDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

protected override bool RunDialog(IntPtr hwndOwner)
        {
            if (Application.OleRequired() != ApartmentState.STA)
            {
                throw new ThreadStateException("The calling thread must be STA.");
            }

            bool result = false;

            NativeInterfaces.IFileSaveDialog dialog = null;

            try
            {
                dialog = CreateDialog();

                OnBeforeShow(dialog);

                FileSaveDialogEvents dialogEvents = new FileSaveDialogEvents(this);
                uint eventCookie;
                dialog.Advise(dialogEvents, out eventCookie);
                try
                {
                    result = dialog.Show(hwndOwner) == NativeConstants.S_OK;
                }
                finally
                {
                    dialog.Unadvise(eventCookie);
                    // Prevent the IFileDialogEvents interface from being collected while the dialog is running.
                    GC.KeepAlive(dialogEvents);
                }
            }
            finally
            {
                if (dialog != null)
                {
                    Marshal.ReleaseComObject(dialog);
                }
            }

            return result;
        }

19 View Source File : VistaFolderBrowserDialog.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

protected override bool RunDialog(IntPtr hwndOwner)
        {
            if (Application.OleRequired() != ApartmentState.STA)
            {
                throw new ThreadStateException("The calling thread must be STA.");
            }

            bool result = false;

            NativeInterfaces.IFileOpenDialog dialog = null;

            try
            {
                dialog = CreateDialog();

                OnBeforeShow(dialog);

                FolderBrowserDialogEvents dialogEvents = new FolderBrowserDialogEvents(this);
                uint eventCookie;
                dialog.Advise(dialogEvents, out eventCookie);
                try
                {
                    result = dialog.Show(hwndOwner) == NativeConstants.S_OK;
                }
                finally
                {
                    dialog.Unadvise(eventCookie);
                    // Prevent the IFileDialogEvents interface from being collected while the dialog is running.
                    GC.KeepAlive(dialogEvents);
                }
            }
            finally
            {
                if (dialog != null)
                {
                    Marshal.ReleaseComObject(dialog);
                }
            }

            return result;
        }

19 View Source File : WebPNative.cs
License : MIT License
Project Creator : 0xC0000054

internal static void WebPSave(
            Surface input,
            Stream output,
            EncodeParams parameters,
            MetadataParams metadata,
            WebPReportProgress callback)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            StreamIOHandler handler = new StreamIOHandler(output);
            WebPWriteImage writeImageCallback = handler.WriteImageCallback;

            WebPEncodingError retVal = WebPEncodingError.Ok;

            if (RuntimeInformation.ProcessArchitecture == Architecture.X64)
            {
                retVal = WebP_x64.WebPSave(writeImageCallback, input.Scan0.Pointer, input.Width, input.Height, input.Stride, parameters, metadata, callback);
            }
            else if (RuntimeInformation.ProcessArchitecture == Architecture.X86)
            {
                retVal = WebP_x86.WebPSave(writeImageCallback, input.Scan0.Pointer, input.Width, input.Height, input.Stride, parameters, metadata, callback);
            }
            else if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)
            {
                retVal = WebP_ARM64.WebPSave(writeImageCallback, input.Scan0.Pointer, input.Width, input.Height, input.Stride, parameters, metadata, callback);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }

            GC.KeepAlive(writeImageCallback);

            if (retVal != WebPEncodingError.Ok)
            {
                switch (retVal)
                {
                    case WebPEncodingError.OutOfMemory:
                    case WebPEncodingError.BitStreamOutOfMemory:
                        throw new OutOfMemoryException(Resources.InsufficientMemoryOnSave);
                    case WebPEncodingError.FileTooBig:
                        throw new WebPException(Resources.EncoderFileTooBig);
                    case WebPEncodingError.ApiVersionMismatch:
                        throw new WebPException(Resources.ApiVersionMismatch);
                    case WebPEncodingError.MetadataEncoding:
                        throw new WebPException(Resources.EncoderMetadataError);
                    case WebPEncodingError.UserAbort:
                        throw new OperationCanceledException();
                    case WebPEncodingError.BadDimension:
                        throw new WebPException(Resources.InvalidImageDimensions);
                    case WebPEncodingError.NullParameter:
                        throw new WebPException(Resources.EncoderNullParameter);
                    case WebPEncodingError.InvalidConfiguration:
                        throw new WebPException(Resources.EncoderInvalidConfiguration);
                    case WebPEncodingError.ParreplacedionZeroOverflow:
                        throw new WebPException(Resources.EncoderParreplacedionZeroOverflow);
                    case WebPEncodingError.ParreplacedionOverflow:
                        throw new WebPException(Resources.EncoderParreplacedionOverflow);
                    case WebPEncodingError.BadWrite:
                        if (handler.WriteException != null)
                        {
                            throw new IOException(Resources.EncoderBadWrite, handler.WriteException);
                        }
                        else
                        {
                            throw new IOException(Resources.EncoderBadWrite);
                        }
                    default:
                        throw new WebPException(Resources.EncoderGenericError);
                }
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : a1xd

[STAThread]
        static void Main()
        {
            var mutex = new System.Threading.Mutex(true, "RawAccelGrapher", out bool result);

            if (!result)
            {
                MessageBox.Show("Another instance of the Raw Accel Grapher is already running.");
                return;
            }

            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

            AppDomain.CurrentDomain.UnhandledException += GlobalUnhandledExceptionHandler;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new RawAcceleration());

            GC.KeepAlive(mutex);      
        }

19 View Source File : DelegateReferenceTests.cs
License : Apache License 2.0
Project Creator : AKruimink

[Fact]
        public void DelegateEquals_EqualsNullDelegate_ShouldReturnFalse()
        {
            // Prepare
            Action referenceAction = () => { };
            var weakReference = new WeakReference(referenceAction);
            var delegateReference = new DelegateReference(referenceAction, false);

            // Act
            GC.KeepAlive(weakReference);

            // replacedert
            replacedert.False(delegateReference.DelegateEquals(null!));
            replacedert.True(weakReference.IsAlive);
        }

19 View Source File : VideoDecodeOutputStreamArguments1.cs
License : MIT License
Project Creator : amerkoleci

internal unsafe void __MarshalFree(ref __Native @ref)
        {
            GC.KeepAlive(OutputTexture2D);
            ConversionArguments.__MarshalFree(ref @ref.ConversionArguments);
            Histograms[0].__MarshalFree(ref @ref.Histograms0);
            Histograms[1].__MarshalFree(ref @ref.Histograms1);
            Histograms[2].__MarshalFree(ref @ref.Histograms2);
            Histograms[3].__MarshalFree(ref @ref.Histograms3);
        }

19 View Source File : ComputePipelineStateDescription.cs
License : MIT License
Project Creator : amerkoleci

internal void __MarshalFree(ref __Native @ref)
        {
            GC.KeepAlive(RootSignature);
            ComputeShader?.__MarshalFree(ref @ref.CS);
            CachedPSO.__MarshalFree(ref @ref.CachedPSO);
        }

19 View Source File : ExistingCollectionDescription.cs
License : MIT License
Project Creator : amerkoleci

unsafe void IStateSubObjectDescriptionMarshal.__MarshalFree(ref IntPtr pDesc)
        {
            GC.KeepAlive(ExistingCollection);
            ref __Native nativeLibrary = ref Unsafe.AsRef<__Native>(pDesc.ToPointer());

            if (nativeLibrary.pExports != null)
            {
                for (int i = 0; i < nativeLibrary.NumExports; i++)
                {
                    Exports[i].__MarshalFree(ref nativeLibrary.pExports[i]);
                }

                Marshal.FreeHGlobal((IntPtr)nativeLibrary.pExports);
            }

            Marshal.FreeHGlobal(pDesc);
        }

19 View Source File : GraphicsPipelineStateDescription.cs
License : MIT License
Project Creator : amerkoleci

internal void __MarshalFree(ref __Native @ref)
        {
            GC.KeepAlive(RootSignature);
            VertexShader?.__MarshalFree(ref @ref.VertexShader);
            PixelShader?.__MarshalFree(ref @ref.PixelShader);
            DomainShader?.__MarshalFree(ref @ref.DomainShader);
            HullShader?.__MarshalFree(ref @ref.HullShader);
            GeometryShader?.__MarshalFree(ref @ref.GeometryShader);
            StreamOutput?.__MarshalFree(ref @ref.StreamOutput);
            BlendState.__MarshalFree(ref @ref.BlendState);
            InputLayout?.__MarshalFree(ref @ref.InputLayout);
            CachedPSO.__MarshalFree(ref @ref.CachedPSO);
        }

19 View Source File : RenderPassEndingAccessResolveParameters.cs
License : MIT License
Project Creator : amerkoleci

internal void __MarshalFree(ref __Native @ref)
        {
            GC.KeepAlive(SrcResource);
            GC.KeepAlive(DstResource);
        }

19 View Source File : IVirtualSurfaceImageSourceNative.cs
License : MIT License
Project Creator : amerkoleci

public unsafe void RegisterForUpdatesNeeded(IVirtualSurfaceUpdatesCallbackNative callback)
        {
            IntPtr callback_ = MarshallingHelpers.ToCallbackPtr<IVirtualSurfaceUpdatesCallbackNative>(callback);
            Result result = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int>)this[10])(NativePointer, (void*)callback_);
            GC.KeepAlive(callback);
            result.CheckError();
        }

19 View Source File : ISurfaceImageSourceManagerNative.cs
License : MIT License
Project Creator : amerkoleci

public unsafe Result FlushAllSurfacesWithDevice(IUnknown device)
        {
            IntPtr device_ = MarshallingHelpers.ToCallbackPtr<IUnknown>(device);
            Result result = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int>)this[3])(NativePointer, (void*)device_);
            GC.KeepAlive(device);
            return result;
        }

19 View Source File : ISurfaceImageSourceNative.cs
License : MIT License
Project Creator : amerkoleci

public unsafe Result SetDevice(IDXGIDevice device)
        {
            IntPtr devicePtr = MarshallingHelpers.ToCallbackPtr<IDXGIDevice>(device);
            Result result = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int>)this[3])(NativePointer, (void*)devicePtr);
            GC.KeepAlive(device);
            result.CheckError();
            return result;
        }

19 View Source File : ISurfaceImageSourceNativeWithD2D.cs
License : MIT License
Project Creator : amerkoleci

public unsafe Result SetDevice(IUnknown device)
        {
            IntPtr device_ = MarshallingHelpers.ToCallbackPtr<IUnknown>(device);
            Result result = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int>)this[3])(NativePointer, (void*)device_);
            GC.KeepAlive(device);
            return result;
        }

19 View Source File : ISwapChainBackgroundPanelNative.cs
License : MIT License
Project Creator : amerkoleci

public unsafe Result SetSwapChain(IDXGISwapChain swapChain)
        {
            IntPtr swapChain_ = MarshallingHelpers.ToCallbackPtr<IDXGISwapChain>(swapChain);
            Result result = ((delegate* unmanaged[Stdcall]<IntPtr, void*, int>)this[3])(NativePointer, (void*)swapChain_);
            GC.KeepAlive(swapChain);
            return result;
        }

19 View Source File : ProgressRunner.cs
License : Apache License 2.0
Project Creator : AmpScm

private void OnDone(object sender, EventArgs e)
            {
                Form si = _invoker;

                if (si != null && si.InvokeRequired)
                {
                    EventHandler eh = new EventHandler(OnDone);
                    try
                    {
                        si.BeginInvoke(eh, new object[] { sender, e });
                    }
                    catch(Exception ex)
                    { 
                        /* Not Catching this exception kills VS */
                        GC.KeepAlive(ex);
                    }
                    return;
                }

                if (si.Visible)
                {
                    si.Close();

                    if (ConfigService != null && ConfigService.Instance.FlashWindowWhenOperationCompletes)
                    {
                        if (DialogOwner != null)
                        {
                            IWin32Window window = DialogOwner.DialogOwner;
                            NativeMethods.FLASHWINFO fw = new NativeMethods.FLASHWINFO();
                            fw.cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(NativeMethods.FLASHWINFO)));
                            fw.hwnd = window.Handle;
                            fw.dwFlags = (Int32)(NativeMethods.FLASHWINFOFLAGS.FLASHW_ALL | NativeMethods.FLASHWINFOFLAGS.FLASHW_TIMERNOFG);
                            fw.dwTimeout = 0;

                            NativeMethods.FlashWindowEx(ref fw);
                        }
                    }
                }
            }

19 View Source File : SvnStatusCache.ShellMonitor.cs
License : Apache License 2.0
Project Creator : AmpScm

void InitializeShellMonitor()
        {
            NotifyWindow nw = new NotifyWindow(this);
            uint cookie = 0;
            try
            {
                NativeMethods.SHChangeNotifyEntry what;
                what.pIdl = IntPtr.Zero;
                what.Recursively = true;

                // We are only interested in Shell events. We let VS handle the real filesystem changes

                // TortoiseSVN has to notify the shell for all his updates, and we just listen to what TortoiseSVN sends us :)

                cookie = NativeMethods.SHChangeNotifyRegister(nw.Handle, 0x0002 | 0x8000, NativeMethods.SHCNE.SHCNE_ALLEVENTS, 0xDEDE, 1, ref what);
            }
            catch(Exception e)
            {
                GC.KeepAlive(e);
                if (nw != null)
                {
                    nw.Dispose();
                    nw = null;
                }
            }
            finally
            {
                _notifyWindow = nw;
                _notifyCookie = cookie;
            }
        }

19 View Source File : RepositoryUrlUtils.cs
License : Apache License 2.0
Project Creator : AmpScm

public static bool TryGuessLayout(IAnkhServiceProvider context, Uri uri, out RepositoryLayoutInfo info)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            else if (uri == null)
                throw new ArgumentNullException("uri");

            info = null;

            uri = SvnTools.GetNormalizedUri(uri);

            GC.KeepAlive(context); // Allow future external hints

            string path;
            if (uri.IsUnc)
            {
                string p = uri.GetComponents(UriComponents.Host | UriComponents.Path, UriFormat.SafeUnescaped);
                if(string.IsNullOrEmpty(p))
                    return false;

                path = "//" + p;
            }
            else
                path = uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);

            if (string.IsNullOrEmpty(path))
                return false;

            if (path[0] != '/' && !uri.IsFile) // Don't do this for files, because it will cause duplicate drive roots
                path = '/' + path;
            if (path[path.Length - 1] != '/')
                path += '/';

            if (string.IsNullOrEmpty(path) || path.Length == 1)
                return false;

            string r = path;

            while (r.Length > 0 && !r.EndsWith("/trunk/", StringComparison.OrdinalIgnoreCase))
            {
                int n = r.LastIndexOf('/', r.Length - 1);

                if (n >= 0)
                {
                    int lastCharIndex = r.Length - 1;
                    // if '/' is the last character, strip and continue
                    // otherwise include '/' to give "/trunk/" check a chance
                    r = r.Substring(0, (n == lastCharIndex) ? n : (n+1));
                }
                else
                    r = "";
            }

            if (!string.IsNullOrEmpty(r))
            {
                info = new RepositoryLayoutInfo();
                info.WorkingRoot = new Uri(uri, r);
                info.WholeProjectRoot = new Uri(uri, r.Substring(0, r.Length - 6));
                info.BranchesRoot = new Uri(info.WholeProjectRoot, "branches/");
                info.SelectedBranch = info.WholeProjectRoot.MakeRelativeUri(info.WorkingRoot);
                return true;
            }

            if (TryFindBranch(uri, path, "branches", true, out info))
                return true;
            else if (TryFindBranch(uri, path, "tags", false, out info))
                return true;    
            else if (TryFindBranch(uri, path, "releases", false, out info))
                return true;

            info = new RepositoryLayoutInfo();
            info.WorkingRoot = new Uri(uri, ".");
            info.WholeProjectRoot = new Uri(info.WorkingRoot, "../");
            info.BranchesRoot = new Uri(info.WholeProjectRoot, "branches/");
            info.TagsRoot = new Uri(info.WholeProjectRoot, "tags/");
            info.SelectedBranch = info.WholeProjectRoot.MakeRelativeUri(info.WorkingRoot);
            return true;
        }

19 View Source File : SvnInfoComboCommand.cs
License : Apache License 2.0
Project Creator : AmpScm

public virtual void OnUpdate(CommandUpdateEventArgs e)
        {
            if (_control == null)
            {
                _control = e.GetService<SvnInfoGridControl>();

                if (_control == null)
                {
                    e.Enabled = false;
                    return;
                }
            }

            GC.KeepAlive(GetNames(e));
        }

19 View Source File : LogRevisionControl.cs
License : Apache License 2.0
Project Creator : AmpScm

void StartFetch(SvnLogArgs args)
        {
            if (DesignMode)
                return;

            fetchCount += args.Limit;

            _clientPool = _context.GetService<ISvnClientPool>();
            _issueService = _context.GetService<IAnkhIssueService>();

            _clientPool.EnsureClient(); // Ensures UI can be setup
            GC.KeepAlive(_issueService?.CurrentIssueRepositorySettings);
            GC.KeepAlive(_issueService?.CurrentIssueRepository);

            _logAction.BeginInvoke(args, null, null);
        }

19 View Source File : SmartListView.cs
License : Apache License 2.0
Project Creator : AmpScm

public void SetSortIcon(int column, SortIcon mode)
        {
            if (DesignMode || !IsHandleCreated || View != View.Details)
                return;

            if (column < 0 || column > Columns.Count)
                throw new ArgumentOutOfRangeException("column", column, "Invalid column number");

            IntPtr hHeader = NativeMethods.SendMessage(Handle, NativeMethods.LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
            IntPtr col = new IntPtr(column);
            NativeMethods.HDITEM hdItem = new NativeMethods.HDITEM();
            IntPtr rtn;

            // Only update the previous item if it existed and if it was a different one.
            hdItem.mask = NativeMethods.HDI_FORMAT;
            rtn = NativeMethods.SendMessage(hHeader, NativeMethods.HDM_GEreplacedEM, col, ref hdItem);

            hdItem.mask = NativeMethods.HDI_FORMAT;
            hdItem.fmt &= ~(NativeMethods.HDF_SORTDOWN | NativeMethods.HDF_SORTUP | NativeMethods.HDF_CHECKBOX | NativeMethods.HDF_CHECKED);
            switch (mode)
            {
                case SortIcon.Ascending:
                    hdItem.fmt |= NativeMethods.HDF_SORTUP;
                    break;
                case SortIcon.Descending:
                    hdItem.fmt |= NativeMethods.HDF_SORTDOWN;
                    break;
            }

            if (column == 0 && CheckBoxes && ShowSelectAllCheckBox)
            {
                if (!_setHeaderStyle)
                {
                    _setHeaderStyle = true;
                    int style = NativeMethods.GetWindowLongW(hHeader, NativeMethods.GWL_STYLE);

                    NativeMethods.SetWindowLongW(hHeader, NativeMethods.GWL_STYLE, style | NativeMethods.HDS_CHECKBOXES);
                }

                hdItem.fmt |= NativeMethods.HDF_CHECKBOX;

                if (SelectAllChecked)
                    hdItem.fmt |= NativeMethods.HDF_CHECKED;
            }

            rtn = NativeMethods.SendMessage(hHeader, NativeMethods.HDM_SEreplacedEM, col, ref hdItem);

            GC.KeepAlive(HeaderHeight);
        }

19 View Source File : InternalDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

public bool RunDiff(AnkhDiffArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("args");
            else if (!HasDiff)
                throw new InvalidOperationException();

            if (_ocw2 == null)
                _ocw2 = GetInterfaceDelegate<OpenComparisonWindow2>(_type_IVsDifferenceService, _vsDifferenceService);

            if (_ocw2 == null)
                return false;

            uint flags = VSDIFFOPT_DetectBinaryFiles;

            if (TempPath != null)
            {
                if (SvnItem.IsBelowRoot(args.BaseFile, TempPath))
                    flags |= VSDIFFOPT_LeftFileIsTemporary;
                if (SvnItem.IsBelowRoot(args.MineFile, TempPath))
                    flags |= VSDIFFOPT_RightFileIsTemporary;
            }

            IVsWindowFrame frame = _ocw2(args.BaseFile, args.MineFile, args.Caption ?? args.Minereplacedle, "", args.Basereplacedle, args.Minereplacedle, args.Label ?? "", null, flags);

            if (frame != null)
            {
                GC.KeepAlive(new DiffMergeInstance(this, frame));

                if (!args.ShowDiffAsDoreplacedent)
                    frame.SetProperty((int)__VSFPROPID.VSFPROPID_FrameMode, (int)VSFRAMEMODE.VSFM_Float);

                return true;
            }

            return false;
        }

19 View Source File : InternalDiff.cs
License : Apache License 2.0
Project Creator : AmpScm

public bool RunMerge(AnkhMergeArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("args");
            else if (!HasMerge)
                throw new InvalidOperationException();

            if (_ormw == null)
            {
                _ormw = GetInterfaceDelegate<OpenAndRegisterMergeWindow>(_type_IVsFileMergeService, _vsFileMergeService);
                _umw = GetInterfaceDelegate<UnregisterMergeWindow>(_type_IVsFileMergeService, _vsFileMergeService);
                _qmws = GetInterfaceDelegate<QueryMergeWindowState>(_type_IVsFileMergeService, _vsFileMergeService);
            }

            if (_ormw == null || _umw == null || _qmws == null)
                return false;

            int cookie;

            IVsWindowFrame frame = _ormw(args.TheirsFile, args.MineFile, args.BaseFile, args.MergedFile,
                                         Path.GetFileName(args.TheirsFile), Path.GetFileName(args.MineFile),
                                         Path.GetFileName(args.BaseFile), Path.GetFileName(args.MergedFile),
                                         args.Theirsreplacedle, args.Minereplacedle, args.Basereplacedle, args.Mergedreplacedle,
                                         Guid.Empty.ToString(), null, null, out cookie);

            if (frame != null)
            {
                GC.KeepAlive(new DiffMergeInstance(this, frame, _umw, _qmws, cookie));

                if (!args.ShowDiffAsDoreplacedent)
                    frame.SetProperty((int)__VSFPROPID.VSFPROPID_FrameMode, (int)VSFRAMEMODE.VSFM_Float);

                return true;
            }

            return false;
        }

19 View Source File : RepositoryTreeView.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnCreateControl()
        {
            base.OnCreateControl();

            if (DesignMode)
                return;

            if (ImageList == null && IconMapper != null)
                ImageList = IconMapper.ImageList;

            GC.KeepAlive(RootNode);
        }

19 View Source File : TransformingAutoEncoders.cs
License : MIT License
Project Creator : anastasios-stamoulis

bool show_translations(bool use_network) {
      if ( use_network ) {
        network = load_best_network();
      }
      var mnist = new Datasets.MNIST();
      var image_size = new int[] { input_shape[0], input_shape[1] };
      var allData = new Data(mnist.train_images, image_size).All();

      for (int index = 0; index < 1000; index++) {
        var img = allData[0][index];
        var T = allData[1][index];
        var img_t = allData[2][index];

        var label = mnist.train_labels[index];
        var digit = Util.argmax(label);
        var mat = convertFloatRowTo2D(img, 28, 28);

        var window_name = $"mnist_{index}_Digit_{digit}";
        // allow the window to be resized
        OpenCvSharp.Cv2.NamedWindow(window_name, OpenCvSharp.WindowMode.Normal);
        OpenCvSharp.Cv2.ImShow(window_name, mat);

        var mat_t = convertFloatRowTo2D(img_t, 28, 28);
        var window_name_T = $"{T[0]}_{T[1]}";
        OpenCvSharp.Cv2.NamedWindow(window_name_T, OpenCvSharp.WindowMode.Normal);
        OpenCvSharp.Cv2.ImShow(window_name_T, mat_t);

        var predicted_mat_t = new OpenCvSharp.Mat();
        if (network != null) {
          var prediction = Model.predict(network, new float[][] { img, T }, computeDevice);
          var predicted_img_t = prediction[0].ToArray();
          predicted_mat_t = convertFloatRowTo2D(predicted_img_t, 28, 28);
          var window_name_predicted_T = $"predicted_{T[0]}_{T[1]}";
          OpenCvSharp.Cv2.NamedWindow(window_name_predicted_T, OpenCvSharp.WindowMode.Normal);
          OpenCvSharp.Cv2.ImShow(window_name_predicted_T, predicted_mat_t);
        }

        OpenCvSharp.Cv2.WaitKey();
        OpenCvSharp.Cv2.DestroyAllWindows();
        //OpenCvSharp.Cv2.DestroyWindow(window_name);
        //OpenCvSharp.Cv2.DestroyWindow(window_name_T);

        GC.KeepAlive(mat);
        GC.KeepAlive(mat_t);
        GC.KeepAlive(predicted_mat_t);
      }
      return false;
    }

19 View Source File : UnixChildProcessStateHelper.cs
License : MIT License
Project Creator : asmichi

public IChildProcessStateHolder SpawnProcess(
            ref ChildProcessStartInfoInternal startInfo,
            string resolvedPath,
            SafeHandle stdIn,
            SafeHandle stdOut,
            SafeHandle stdErr)
        {
            var arguments = startInfo.Arguments;
            var environmentVariables = startInfo.EnvironmentVariables;
            var workingDirectory = startInfo.WorkingDirectory;

            Span<int> fds = stackalloc int[3];
            int handleCount = 0;
            uint flags = 0;
            if (stdIn != null)
            {
                fds[handleCount++] = stdIn.DangerousGetHandle().ToInt32();
                flags |= RequestFlagsRedirectStdin;
            }
            if (stdOut != null)
            {
                fds[handleCount++] = stdOut.DangerousGetHandle().ToInt32();
                flags |= RequestFlagsRedirectStdout;
            }
            if (stdErr != null)
            {
                fds[handleCount++] = stdErr.DangerousGetHandle().ToInt32();
                flags |= RequestFlagsRedirectStderr;
            }

            if (startInfo.CreateNewConsole)
            {
                flags |= RequestFlagsCreateNewProcessGroup;
            }
            else
            {
                Debug.replacedert(!startInfo.AllowSignal);
            }

            // If AttachToCurrentConsole (== !startInfo.AllowSignal), leave the process running after we (the parent) exit.
            // After being orphaned (and possibly reparented to the shell), it may continue running or may be terminated by SIGTTIN/SIGTTOU.
            if (startInfo.AllowSignal)
            {
                flags |= RequestFlagsEnableAutoTermination;
            }

            using var bw = new MyBinaryWriter(InitialBufferCapacity);
            var stateHolder = UnixChildProcessState.Create(this, startInfo.AllowSignal);
            try
            {
                bw.Write(stateHolder.State.Token);
                bw.Write(flags);
                bw.Write(workingDirectory);
                bw.Write(resolvedPath);

                bw.Write((uint)(arguments.Count + 1));
                bw.Write(resolvedPath);
                foreach (var x in arguments)
                {
                    bw.Write(x);
                }

                if (!startInfo.UseCustomEnvironmentVariables)
                {
                    // Send the environment variables of this process to the helper process.
                    //
                    // NOTE: We cannot cache or detect updates to the environment block; only the runtime can.
                    //       Concurrently invoking getenv and setenv is a racy operation; therefore the runtime
                    //       employs a process-global lock.
                    //
                    //       Fortunately, the caller can take a snapshot of environment variables theirselves.
                    var processEnvVars = Environment.GetEnvironmentVariables();
                    var envVarCount = processEnvVars.Count;
                    bw.Write((uint)envVarCount);

                    var sortedEnvVars = ArrayPool<KeyValuePair<string, string>>.Shared.Rent(envVarCount);
                    try
                    {
                        EnvironmentVariableListUtil.ToSortedKeyValuePairs(processEnvVars, sortedEnvVars);

                        foreach (var (name, value) in sortedEnvVars.replacedpan<KeyValuePair<string, string>>().Slice(0, envVarCount))
                        {
                            bw.WriteEnvironmentVariable(name, value);
                        }
                    }
                    finally
                    {
                        ArrayPool<KeyValuePair<string, string>>.Shared.Return(sortedEnvVars);
                    }
                }
                else
                {
                    bw.Write((uint)environmentVariables.Length);
                    foreach (var (name, value) in environmentVariables.Span)
                    {
                        bw.WriteEnvironmentVariable(name, value);
                    }
                }

                // Work around https://github.com/microsoft/WSL/issues/6490
                // On WSL 1, if you call recvmsg multiple times to fully receive data sent with sendmsg,
                // the fds will be duplicated for each recvmsg call.
                // Send only fixed length of of data with the fds and receive that much data with one recvmsg call.
                // That will be safer anyway.
                Span<byte> header = stackalloc byte[sizeof(uint) * 2];
                if (!BitConverter.TryWriteBytes(header, (uint)UnixHelperProcessCommand.SpawnProcess)
                    || !BitConverter.TryWriteBytes(header.Slice(sizeof(uint)), bw.Length))
                {
                    Debug.Fail("Should never fail.");
                }

                var subchannel = _helperProcess.RentSubchannelAsync(default).AsTask().GetAwaiter().GetResult();

                try
                {
                    subchannel.SendExactBytesAndFds(header, fds.Slice(0, handleCount));

                    subchannel.SendExactBytes(bw.GetBuffer());
                    GC.KeepAlive(stdIn);
                    GC.KeepAlive(stdOut);
                    GC.KeepAlive(stdErr);

                    var (error, processId) = subchannel.ReceiveCommonResponse();
                    if (error > 0)
                    {
                        throw new Win32Exception(error);
                    }
                    else if (error < 0)
                    {
                        throw new AsmichiChildProcessInternalLogicErrorException(
                            string.Format(CultureInfo.InvariantCulture, "Internal logic error: Bad request {0}.", error));
                    }

                    stateHolder.State.SetProcessId(processId);

                    return stateHolder;
                }
                finally
                {
                    _helperProcess.ReturnSubchannel(subchannel);
                }
            }
            catch
            {
                stateHolder.Dispose();
                throw;
            }
        }

19 View Source File : BackgroundDocumentGenerator.cs
License : Apache License 2.0
Project Creator : aspnet

private void ReportError(Exception ex)
        {
            GC.KeepAlive(Task.Factory.StartNew(
                () => _projectManager.ReportError(ex),
                CancellationToken.None,
                TaskCreationOptions.None,
                _foregroundDispatcher.ForegroundScheduler));
        }

19 View Source File : DelayedRegionCreationBehaviorFixture.cs
License : MIT License
Project Creator : AvaloniaCommunity

[TestMethod]
        public void BehaviorDoesNotPreventControlFromBeingGarbageCollected()
        {
            var control = new MockFrameworkElement();
            WeakReference controlWeakReference = new WeakReference(control);

            var accessor = new MockRegionManagerAccessor
                               {
                                   GetRegionName = d => "myRegionName"
                               };

            var behavior = this.GetBehavior(control, accessor);
            behavior.Attach();

            replacedert.IsTrue(controlWeakReference.IsAlive);
            GC.KeepAlive(control);

            control = null;
            GC.Collect();

            replacedert.IsFalse(controlWeakReference.IsAlive);
        }

19 View Source File : DelayedRegionCreationBehaviorFixture.cs
License : MIT License
Project Creator : AvaloniaCommunity

[TestMethod]
        public void BehaviorDoesNotPreventControlFromBeingGarbageCollectedWhenRegionWasCreated()
        {
            var control = new MockFrameworkElement();
            WeakReference controlWeakReference = new WeakReference(control);

            var accessor = new MockRegionManagerAccessor
            {
                GetRegionName = d => "myRegionName"
            };

            var behavior = this.GetBehavior(control, accessor);
            behavior.Attach();
            accessor.UpdateRegions();
            
            replacedert.IsTrue(controlWeakReference.IsAlive);
            GC.KeepAlive(control);

            control = null;
            GC.Collect();

            replacedert.IsFalse(controlWeakReference.IsAlive);
        }

19 View Source File : DelayedRegionCreationBehaviorFixture.cs
License : MIT License
Project Creator : AvaloniaCommunity

[TestMethod]
        public void ShouldCleanupBehaviorOnceRegionIsCreated()
        {
            var control = new MockFrameworkElement();
            var control2 = new MockFrameworkContentElement();

            var accessor = new MockRegionManagerAccessor
            {
                GetRegionName = d => "myRegionName"
            };

            var behavior = this.GetBehavior(control, accessor);
            WeakReference behaviorWeakReference = new WeakReference(behavior);
            behavior.Attach();
            accessor.UpdateRegions();
            replacedert.IsTrue(behaviorWeakReference.IsAlive);
            GC.KeepAlive(behavior);

            behavior = null;
            GC.Collect();

            replacedert.IsFalse(behaviorWeakReference.IsAlive);

            var behavior2 = this.GetBehavior(control2, accessor);
            WeakReference behaviorWeakReference2 = new WeakReference(behavior2);
            behavior2.Attach();
            accessor.UpdateRegions();
            replacedert.IsTrue(behaviorWeakReference2.IsAlive);
            GC.KeepAlive(behavior2);

            behavior2 = null;
            GC.Collect();

            replacedert.IsFalse(behaviorWeakReference2.IsAlive);
        }

19 View Source File : RegionManagerRegistrationBehaviorFixture.cs
License : MIT License
Project Creator : AvaloniaCommunity

[TestMethod]
        public void BehaviorDoesNotPreventRegionManagerFromBeingGarbageCollected()
        {
            var control = new MockFrameworkElement();
            var regionManager = new MockRegionManager();
            var regionManagerWeakReference = new WeakReference(regionManager);

            var accessor = new MockRegionManagerAccessor
            {
                GetRegionName = d => "myRegionName",
                GetRegionManager = d => regionManager
            };

            var behavior = new RegionManagerRegistrationBehavior()
            {
                RegionManagerAccessor = accessor,
                Region = new MockPresentationRegion(),
                HostControl = control
            };
            behavior.Attach();

            replacedert.IsTrue(regionManagerWeakReference.IsAlive);
            GC.KeepAlive(regionManager);

            regionManager = null;

            GC.Collect();

            replacedert.IsFalse(regionManagerWeakReference.IsAlive);
        }

19 View Source File : TextAnchorTest.cs
License : MIT License
Project Creator : AvaloniaUI

[Test]
		public void CreateAnchors()
		{
			List<TextAnchor> anchors = new List<TextAnchor>();
			List<int> expectedOffsets = new List<int>();
			doreplacedent.Text = new string(' ', 1000);
			for (int i = 0; i < 1000; i++) {
				int offset = rnd.Next(1000);
				anchors.Add(doreplacedent.CreateAnchor(offset));
				expectedOffsets.Add(offset);
			}
			for (int i = 0; i < anchors.Count; i++) {
				replacedert.AreEqual(expectedOffsets[i], anchors[i].Offset);
			}
			GC.KeepAlive(anchors);
		}

19 View Source File : TextAnchorTest.cs
License : MIT License
Project Creator : AvaloniaUI

[Test]
		public void CreateAndMoveAnchors()
		{
			List<TextAnchor> anchors = new List<TextAnchor>();
			List<int> expectedOffsets = new List<int>();
			doreplacedent.Text = new string(' ', 1000);
			for (int t = 0; t < 250; t++) {
				//Console.Write("t = " + t + " ");
				int c = rnd.Next(50);
				switch (rnd.Next(5)) {
					case 0:
						//Console.WriteLine("Add c=" + c + " anchors");
						for (int i = 0; i < c; i++) {
							int offset = rnd.Next(doreplacedent.TextLength);
							TextAnchor anchor = doreplacedent.CreateAnchor(offset);
							if (rnd.Next(2) == 0)
								anchor.MovementType = AnchorMovementType.BeforeInsertion;
							else
								anchor.MovementType = AnchorMovementType.AfterInsertion;
							anchor.SurviveDeletion = rnd.Next(2) == 0;
							anchors.Add(anchor);
							expectedOffsets.Add(offset);
						}
						break;
					case 1:
						if (c <= anchors.Count) {
							//Console.WriteLine("Remove c=" + c + " anchors");
							anchors.RemoveRange(0, c);
							expectedOffsets.RemoveRange(0, c);
							GC.Collect();
						}
						break;
					case 2:
						int insertOffset = rnd.Next(doreplacedent.TextLength);
						int insertLength = rnd.Next(1000);
						//Console.WriteLine("insertOffset=" + insertOffset + " insertLength="+insertLength);
						doreplacedent.Insert(insertOffset, new string(' ', insertLength));
						for (int i = 0; i < anchors.Count; i++) {
							if (anchors[i].MovementType == AnchorMovementType.BeforeInsertion) {
								if (expectedOffsets[i] > insertOffset)
									expectedOffsets[i] += insertLength;
							} else {
								if (expectedOffsets[i] >= insertOffset)
									expectedOffsets[i] += insertLength;
							}
						}
						break;
					case 3:
						int removalOffset = rnd.Next(doreplacedent.TextLength);
						int removalLength = rnd.Next(doreplacedent.TextLength - removalOffset);
						//Console.WriteLine("RemovalOffset=" + removalOffset + " RemovalLength="+removalLength);
						doreplacedent.Remove(removalOffset, removalLength);
						for (int i = anchors.Count - 1; i >= 0; i--) {
							if (expectedOffsets[i] > removalOffset && expectedOffsets[i] < removalOffset + removalLength) {
								if (anchors[i].SurviveDeletion) {
									expectedOffsets[i] = removalOffset;
								} else {
									replacedert.IsTrue(anchors[i].IsDeleted);
									anchors.RemoveAt(i);
									expectedOffsets.RemoveAt(i);
								}
							} else if (expectedOffsets[i] > removalOffset) {
								expectedOffsets[i] -= removalLength;
							}
						}
						break;
					case 4:
						int replaceOffset = rnd.Next(doreplacedent.TextLength);
						int replaceRemovalLength = rnd.Next(doreplacedent.TextLength - replaceOffset);
						int replaceInsertLength = rnd.Next(1000);
						//Console.WriteLine("ReplaceOffset=" + replaceOffset + " RemovalLength="+replaceRemovalLength + " InsertLength=" + replaceInsertLength);
						doreplacedent.Replace(replaceOffset, replaceRemovalLength, new string(' ', replaceInsertLength));
						for (int i = anchors.Count - 1; i >= 0; i--) {
							if (expectedOffsets[i] > replaceOffset && expectedOffsets[i] < replaceOffset + replaceRemovalLength) {
								if (anchors[i].SurviveDeletion) {
									if (anchors[i].MovementType == AnchorMovementType.AfterInsertion)
										expectedOffsets[i] = replaceOffset + replaceInsertLength;
									else
										expectedOffsets[i] = replaceOffset;
								} else {
									replacedert.IsTrue(anchors[i].IsDeleted);
									anchors.RemoveAt(i);
									expectedOffsets.RemoveAt(i);
								}
							} else if (expectedOffsets[i] > replaceOffset) {
								expectedOffsets[i] += replaceInsertLength - replaceRemovalLength;
							} else if (expectedOffsets[i] == replaceOffset && replaceRemovalLength == 0 && anchors[i].MovementType == AnchorMovementType.AfterInsertion) {
								expectedOffsets[i] += replaceInsertLength - replaceRemovalLength;
							}
						}
						break;
				}
				replacedert.AreEqual(anchors.Count, expectedOffsets.Count);
				for (int j = 0; j < anchors.Count; j++) {
					replacedert.AreEqual(expectedOffsets[j], anchors[j].Offset);
				}
			}
			GC.KeepAlive(anchors);
		}

19 View Source File : TextAnchorTest.cs
License : MIT License
Project Creator : AvaloniaUI

[Test]
		public void CreateAndGCAnchors()
		{
			List<TextAnchor> anchors = new List<TextAnchor>();
			List<int> expectedOffsets = new List<int>();
			doreplacedent.Text = new string(' ', 1000);
			for (int t = 0; t < 250; t++) {
				int c = rnd.Next(50);
				if (rnd.Next(2) == 0) {
					for (int i = 0; i < c; i++) {
						int offset = rnd.Next(1000);
						anchors.Add(doreplacedent.CreateAnchor(offset));
						expectedOffsets.Add(offset);
					}
				} else if (c <= anchors.Count) {
					anchors.RemoveRange(0, c);
					expectedOffsets.RemoveRange(0, c);
					GC.Collect();
				}
				for (int j = 0; j < anchors.Count; j++) {
					replacedert.AreEqual(expectedOffsets[j], anchors[j].Offset);
				}
			}
			GC.KeepAlive(anchors);
		}

19 View Source File : WeakReferenceTests.cs
License : MIT License
Project Creator : AvaloniaUI

void DoreplacedentDoesNotHoldReferenceToTextArea()
        {
            var textDoreplacedent = new TextDoreplacedent();
            var wr = CreateControl<TextArea>(t => t.Doreplacedent = textDoreplacedent);
            replacedert.IsFalse(wr.IsAlive);
            GC.KeepAlive(textDoreplacedent);
        }

19 View Source File : WeakReferenceTests.cs
License : MIT License
Project Creator : AvaloniaUI

void DoreplacedentDoesNotHoldReferenceToTextEditor()
        {
            var textDoreplacedent = new TextDoreplacedent();
            var wr = CreateControl<TextEditor>(t => t.Doreplacedent = textDoreplacedent);
            replacedert.IsFalse(wr.IsAlive);
            GC.KeepAlive(textDoreplacedent);
        }

19 View Source File : WeakReferenceTests.cs
License : MIT License
Project Creator : AvaloniaUI

[Test]
        public void DoreplacedentDoesNotHoldReferenceToLineMargin()
        {
            TextDoreplacedent textDoreplacedent = new TextDoreplacedent();
            var wr = CreateControl<TextView>(t =>
            {
                t.Doreplacedent = textDoreplacedent;
                new LineNumberMargin { TextView = t };
            });

            replacedert.IsFalse(wr.IsAlive);
            GC.KeepAlive(textDoreplacedent);
        }

19 View Source File : LetsEncryptCertificateFetcher.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ayende

private void Renew(object state)
        {
            var serverCertificate = _certificate;
            if (serverCertificate != null && (DateTime.Today - serverCertificate.NotAfter).TotalDays > 14)
                return;
            // ignoring exception, we'll retry anyway
            FetchCertificateFromLetsEncryptAsync().ContinueWith(t => GC.KeepAlive(t.Exception));
        }

19 View Source File : TextureHelper.cs
License : MIT License
Project Creator : bonsai-rx

public static void UpdateTexture(TextureTarget target, PixelInternalFormat? internalFormat, IplImage image)
        {
            PixelType pixelType;
            PixelFormat pixelFormat;
            if (image == null) throw new ArgumentNullException("image");
            UnpackPixelStore(image, out pixelFormat, out pixelType);
            if (internalFormat.HasValue)
            {
                GL.TexImage2D(target, 0, internalFormat.Value, image.Width, image.Height, 0, pixelFormat, pixelType, image.ImageData);
            }
            else GL.TexSubImage2D(target, 0, 0, 0, image.Width, image.Height, pixelFormat, pixelType, image.ImageData);
            GC.KeepAlive(image);
        }

19 View Source File : Unity3DRider.cs
License : MIT License
Project Creator : bonzaiferroni

public static List<IntPtr> GetTopLevelWindowHandles()
      {
        var retval = new List<IntPtr>();
        EnumWindowsProc callback = (hwnd, param) =>
        {
          retval.Add(hwnd);
          return 1;
        };
        EnumWindows(Marshal.GetFunctionPointerForDelegate(callback), IntPtr.Zero);
        GC.KeepAlive(callback);
        return retval;
      }

19 View Source File : FolderSelectDialog.cs
License : MIT License
Project Creator : botman99

public bool ShowDialog(IntPtr hWndOwner)
		{
			if( Environment.OSVersion.Version.Major >= 6 )  // Vista/Win7/Win8/Win10
			{
				name_string = "System.Windows.Forms";
				replacedembly = null;
				replacedemblyName[] referencedreplacedemblies = replacedembly.GetExecutingreplacedembly().GetReferencedreplacedemblies();
				foreach (replacedemblyName replacedemblyName in referencedreplacedemblies)
				{
					if (replacedemblyName.FullName.StartsWith(name_string))
					{
						replacedembly = replacedembly.Load(replacedemblyName);
						break;
					}
				}

				Type typeIFileDialog = GetType("FileDialogNative.IFileDialog");
				object dialog = Call(OpenFileDir.GetType(), OpenFileDir, "CreateVistaDialog");
				Call(OpenFileDir.GetType(), OpenFileDir, "OnBeforeVistaDialog", dialog);

				uint options = (uint)Call(typeof(System.Windows.Forms.FileDialog), OpenFileDir, "GetOptions");
				options = options | (uint)GetEnum("FileDialogNative.FOS", "FOS_PICKFOLDERS");
				Call(typeIFileDialog, dialog, "SetOptions", options);

				object pFileDialogEvent = New("FileDialog.VistaDialogEvents", OpenFileDir);

				uint num_parms = 0;

				object[] parameters = new object[] { pFileDialogEvent, num_parms };
				Call(typeIFileDialog, dialog, "Advise", parameters);

				num_parms = (uint)parameters[1];

				try
				{
					// show the dialog
					int count = (int)Call(typeIFileDialog, dialog, "Show", hWndOwner);
					return (count == 0);
				}
				finally
				{
					// remove event handler
					Call(typeIFileDialog, dialog, "Unadvise", num_parms);
					GC.KeepAlive(pFileDialogEvent);
				}
			}
			else  // XP and earlier
			{
				FolderBrowserDialog FolderBrowser = new FolderBrowserDialog();

				FolderBrowser.Description = this.replacedle;
				FolderBrowser.SelectedPath = this.InitialDirectory;
				FolderBrowser.ShowNewFolderButton = false;

				DialogResult dialog_result = FolderBrowser.ShowDialog();
				if( dialog_result == DialogResult.OK )
				{
					OpenFileDir.FileName = FolderBrowser.SelectedPath;
					return true;
				}
			}
			return false;
		}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : brhinescot

[STAThread]
        private static void Main()
        {
            bool isFirstInstance;
            Mutex mutex = new Mutex(false, "Local\\Cropper", out isFirstInstance);
            if (Configuration.Current.AllowMultipleInstances || isFirstInstance)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                MainCropForm mainCropForm = new MainCropForm();

                mainCropForm.Closed += HandleMainCropFormClosed;
                Application.Run(mainCropForm);
                GC.KeepAlive(mutex);
            }
        }

19 View Source File : MixedReadWriteOverheadTests.cs
License : Apache License 2.0
Project Creator : busterwood

public void BitPseudoLru_cache_half(Test t)
        {
            foreach (var items in testSizes)
            {
                string[] keys = CreateKeyStrings(items);
                var pm = new PerformaceMonitor(start: true);

                var cache = new BitPseudoLruMap<string, string>(valueIsKey, items / 2);
                ReadMixKeys(keys, cache, t);

                pm.Stop();
                t.Log($"BitPseudoLru_cache_half of {items} items {pm.Stop()}");
                GC.KeepAlive(cache);
                GC.KeepAlive(keys);

            }
        }

19 View Source File : MixedReadWriteOverheadTests.cs
License : Apache License 2.0
Project Creator : busterwood

public void generational_cache_half(Test t)
        {
            foreach (var items in testSizes)
            {
                string[] keys = CreateKeyStrings(items);
                var pm = new PerformaceMonitor(start: true);

                var cache = valueIsKey.WithGenerationalCache(items / 4, null);
                ReadMixKeys(keys, cache, t);
                cache.Dispose();
                pm.Stop();
                t.Log($"generational_cache_half of {items} items {pm.Stop()}");
                GC.KeepAlive(cache);
                GC.KeepAlive(keys);
            }
        }

19 View Source File : MixedReadWriteOverheadTests.cs
License : Apache License 2.0
Project Creator : busterwood

public void concurrent_dictionary_memory_overhead(Test t)
        {
            foreach (var items in testSizes)
            {
                string[] keys = CreateKeyStrings(items);
                var pm = new PerformaceMonitor(start: true);

                var cache = new ConcurrentDictionary<string, string>();
                ReadMixKeys(keys, cache, t);

                pm.Stop();
                t.Log($"concurrent_dictionary_memory_overhead of {items} items {pm.Stop()}");
                GC.KeepAlive(cache);
                GC.KeepAlive(keys);
            }
        }

19 View Source File : ThunderingHerdOverheadTests.cs
License : Apache License 2.0
Project Creator : busterwood

public void concurrent_dictionary_memory_overhead(Test t)
        {
            var cache = new ConcurrentDictionary<string, string>();
            ReadMixKeys(keys, cache, t);
            
            pm.Stop();
            Console.WriteLine($"concurrent dictionary {valueIsKey.HitCount} hits to underlying data source, {pm.Stop()}");
            GC.KeepAlive(cache);
            GC.KeepAlive(keys);
        }

See More Examples