Exemplo n.º 1
0
        internal unsafe static void Initialize(GCType gcType)
        {
            traceablePtrs       = new ManagedPtrAccounting();
            traceablePinnedPtrs = new ManagedPtrAccounting();
            staticPtrs          = new StaticPtrAccounting();

            assertRTypeHeaders       = new AssertRTypeHeaders();
            forGCAssertRTypeHeaders  = assertRTypeHeaders;
            runtimeTypeReckoner      = new RuntimeTypeReckoner();
            forGCRuntimeTypeReckoner = runtimeTypeReckoner;
            runtimeTypeMapper        = new RuntimeTypeMapper();
            forGCRuntimeTypeMapper   = runtimeTypeMapper;
            instanceReckoner         = new InstanceReckoner();
            forGCInstanceReckoner    = instanceReckoner;

            switch (gcType)
            {
            case GCType.MarkSweepCollector: {
                forGCAssertRTypeHeaders  = new SegregatedFreeList.ObjectVisitorWrapper(assertRTypeHeaders);
                forGCRuntimeTypeReckoner = new SegregatedFreeList.ObjectVisitorWrapper(runtimeTypeReckoner);
                forGCRuntimeTypeMapper   = new SegregatedFreeList.ObjectVisitorWrapper(runtimeTypeMapper);
                forGCInstanceReckoner    = new SegregatedFreeList.ObjectVisitorWrapper(instanceReckoner);
                break;
            }
            }

            table = new RuntimeTypeAccounting[TABLE_SIZE];

            MemoryAccounting.initialized = true;
        }
Exemplo n.º 2
0
 public override void OnSCDestroy()
 {
     base.OnSCDestroy();
     GCData     = null;
     GCType     = GCType.Null;
     GCName     = "";
     tpPosition = Vector2.zero;
 }
Exemplo n.º 3
0
        public GCWorker()
        {
            GCThread  = null;
            GCWorking = false;

            GCWorker._GCRequested = false;
            GCWorker._GCGen       = -1;
            GCWorker._GCType      = GCType.GCOptimized;
        }
Exemplo n.º 4
0
 public static Transform KSTransform(GCType type = GCType.Right)
 {
     if (KSRight && type == GCType.Right)
     {
         return(KSRight.inputDeviceKSPartUI.ModelGC.transform);
     }
     else if (KSLeft && type == GCType.Left)
     {
         return(KSLeft.inputDeviceKSPartUI.ModelGC.transform);
     }
     return(null);
 }
Exemplo n.º 5
0
 ///API-No.153
 /// <summary>
 /// BTRight/BTLeft的四元数,全局坐标
 /// </summary>
 /// <param name="type">右手柄 BTRight /  左手柄 BTLeft</param>
 /// <returns></returns>
 public static Quaternion KSRotation(GCType type = GCType.Right)
 {
     if (KSRight && type == GCType.Right)
     {
         return(KSRight.inputDataKS.rotation);
     }
     else if (KSLeft && type == GCType.Left)
     {
         return(KSLeft.inputDataKS.rotation);
     }
     return(Quaternion.identity);
 }
Exemplo n.º 6
0
 ///API-No.154
 /// <summary>
 /// BTRight/BTLeft的位置信息,全局坐标
 /// </summary>
 /// <param name="type">右手柄 BTRight /  左手柄 BTLeft</param>
 /// <returns></returns>
 public static Vector3 KSPosition(GCType type = GCType.Right)
 {
     if (KSRight && type == GCType.Right)
     {
         return(KSRight.inputDataKS.position);
     }
     else if (KSLeft && type == GCType.Left)
     {
         return(KSLeft.inputDataKS.position);
     }
     return(Vector3.zero);
 }
Exemplo n.º 7
0
        private void Collect(int gen = -1, GCType type = GCType.GCOptimized)
        {
            if (gen == -1)
            {
                gen = GC.MaxGeneration;
            }

            // GC 가 Request 되었다면 예외적으로 수행
            if (!KanColleSettings.UseMemoryOptimize && !GCWorker._GCRequested)
            {
                return;
            }
            GCWorker._GCRequested = false;

            GC.Collect(gen, type == GCType.GCOptimized ? GCCollectionMode.Optimized : GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();

            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Filter events according to checkboxes
        /// </summary>
        IEnumerable <GcEventWrapper> FilterEvent()
        {
            bool no_g0    = m_g0.UnChecked();
            bool no_g1    = m_g1.UnChecked();
            bool no_g2Blk = m_g2Blocking.UnChecked();
            bool no_g2Bak = m_g2Background.UnChecked();

            bool no_inducedBlocking = m_inducedBlocking.UnChecked();
            bool no_inducedNonBlock = m_inducedNonblocking.UnChecked();
            bool no_lowMemory       = m_lowMemory.UnChecked();
            bool no_allocSOH        = m_allocSOH.UnChecked();
            bool no_allocLOH        = m_AllocLOH.UnChecked();

            foreach (GcEventWrapper er in m_gcEvents)
            {
                TraceGC e = er.Event;

                GCType typ = e.Type;

                switch (e.Generation)
                {
                case 0:
                    if (no_g0)
                    {
                        continue;
                    }
                    break;

                case 1:
                    if (no_g1)
                    {
                        continue;
                    }
                    break;

                case 2:
                    if (no_g2Blk && (typ == GCType.NonConcurrentGC))
                    {
                        continue;
                    }
                    if (no_g2Bak && (typ == GCType.BackgroundGC))
                    {
                        continue;
                    }
                    break;
                }

                switch (e.Reason)
                {
                case GCReason.OutOfSpaceSOH:
                case GCReason.AllocSmall:
                    if (no_allocSOH)
                    {
                        continue;
                    }
                    break;

                case GCReason.InducedNotForced:
                case GCReason.Induced:
                    if (no_inducedBlocking && (typ == GCType.NonConcurrentGC))
                    {
                        continue;
                    }
                    if (no_inducedNonBlock && (typ == GCType.BackgroundGC))
                    {
                        continue;
                    }
                    break;

                case GCReason.OutOfSpaceLOH:
                case GCReason.AllocLarge:
                    if (no_allocLOH)
                    {
                        continue;
                    }
                    break;

                case GCReason.LowMemory:
                case GCReason.InducedLowMemory:
                    if (no_lowMemory)
                    {
                        continue;
                    }
                    break;

                case GCReason.Empty:
                case GCReason.Internal:
                default:
                    break;
                }

                yield return(er);
            }
        }
Exemplo n.º 9
0
        internal unsafe static void Report(GCType gcType)
        {
            if (!MemoryAccounting.initialized)
            {
                VTable.DebugPrint("MemoryAccounting invoked before"
                                  + " initialization was completed!\n");
                return;
            }

            VTable.DebugPrint("\nCollector: ");
            switch (gcType)
            {
            case GCType.AdaptiveCopyingCollector: {
                VTable.DebugPrint("Adaptive Copying\n");
                break;
            }

            case GCType.MarkSweepCollector: {
                VTable.DebugPrint("Mark-Sweep\n");
                break;
            }

            case GCType.SemispaceCollector: {
                VTable.DebugPrint("Semispace\n");
                break;
            }

            case GCType.SlidingCollector: {
                VTable.DebugPrint("Sliding\n");
                break;
            }

            case GCType.ConcurrentMSCollector: {
                VTable.DebugPrint("Concurrent Mark-Sweep\n");
                break;
            }

            case GCType.ReferenceCountingCollector: {
                VTable.DebugPrint("Reference Counting\n");
                VTable.NotImplemented();
                return;   // Not supported yet.
            }

#if !SINGULARITY
            case GCType.DeferredReferenceCountingCollector: {
                VTable.DebugPrint("Deferred Reference Counting\n");
                VTable.NotImplemented();
                return;   // Not supported yet.
            }
#endif
            default: {
                VTable.NotReached("Unknown GC type: " + gcType);
                break;
            }
            }

            uint pageSize = (uint)(PageTable.PageSize >> 10);
            VTable.DebugPrint("\nPage size: {0}KB\nVM size: {1} KB\n",
                              __arglist(pageSize,
                                        pageSize * (uint)PageTable.pageTableCount));

            ReportNonGCDetails();
            ReportStackDetails();
            ReportHeapDetails();
        }
Exemplo n.º 10
0
        private static void TestMARSSessionPooling(string caseName, string connectionString, CommandType commandType,
                                           ExecuteType executeType, ReaderTestType readerTestType, GCType gcType)
        {
            SqlCommand[] cmd = new SqlCommand[CONCURRENT_COMMANDS];
            SqlDataReader[] gch = new SqlDataReader[CONCURRENT_COMMANDS];

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
                {
                    // Prepare all commands
                    cmd[i] = con.CreateCommand();
                    switch (commandType)
                    {
                        case CommandType.Text:
                            cmd[i].CommandText = _COMMAND_SQL;
                            cmd[i].CommandTimeout = 120;
                            break;
                        case CommandType.StoredProcedure:
                            cmd[i].CommandText = _COMMAND_RPC;
                            cmd[i].CommandTimeout = 120;
                            cmd[i].CommandType = CommandType.StoredProcedure;
                            break;
                    }
                }

                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
                {
                    switch (executeType)
                    {
                        case ExecuteType.ExecuteScalar:
                            cmd[i].ExecuteScalar();
                            break;
                        case ExecuteType.ExecuteNonQuery:
                            cmd[i].ExecuteNonQuery();
                            break;
                        case ExecuteType.ExecuteReader:
                            if (readerTestType != ReaderTestType.ReaderGC)
                                gch[i] = cmd[i].ExecuteReader();

                            switch (readerTestType)
                            {
                                case ReaderTestType.ReaderClose:
                                    {
                                        gch[i].Dispose();
                                        break;
                                    }
                                case ReaderTestType.ReaderDispose:
                                    gch[i].Dispose();
                                    break;
                                case ReaderTestType.ReaderGC:
                                    gch[i] = null;
                                    WeakReference weak = OpenReaderThenNullify(cmd[i]);
                                    GC.Collect();

                                    if (gcType == GCType.Wait)
                                    {
                                        GC.WaitForPendingFinalizers();
                                        Assert.False(weak.IsAlive, "Error - target still alive!");
                                    }
                                    break;
                                case ReaderTestType.ConnectionClose:
                                    GC.SuppressFinalize(gch[i]);
                                    con.Close();
                                    con.Open();
                                    break;
                                case ReaderTestType.NoCloses:
                                    GC.SuppressFinalize(gch[i]);
                                    break;
                            }
                            break;
                    }

                    if (readerTestType != ReaderTestType.NoCloses)
                    {
                        con.Close();
                        con.Open(); // Close and open, to re-assure collection!
                    }

                    SqlCommand verificationCmd = con.CreateCommand();

                    verificationCmd.CommandText = COMMAND_STATUS;
                    using (SqlDataReader rdr = verificationCmd.ExecuteReader())
                    {
                        rdr.Read();
                        int connections = (int)rdr.GetValue(0);
                        rdr.NextResult();
                        rdr.Read();
                        int requests = (int)rdr.GetValue(0);

                        switch (executeType)
                        {
                            case ExecuteType.ExecuteScalar:
                            case ExecuteType.ExecuteNonQuery:
                                // 1 for connection, 1 for command
                                Assert.True(connections == 2, "Failure - incorrect number of connections for ExecuteScalar! #connections: " + connections);

                                // only 1 executing
                                Assert.True(requests == 1, "Failure - incorrect number of requests for ExecuteScalar! #requests: " + requests);
                                break;
                            case ExecuteType.ExecuteReader:
                                switch (readerTestType)
                                {
                                    case ReaderTestType.ReaderClose:
                                    case ReaderTestType.ReaderDispose:
                                    case ReaderTestType.ConnectionClose:
                                        // 1 for connection, 1 for command
                                        Assert.True(connections == 2, "Failure - Incorrect number of connections for ReaderClose / ReaderDispose / ConnectionClose! #connections: " + connections);

                                        // only 1 executing
                                        Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderClose/ReaderDispose/ConnectionClose! #requests: " + requests);
                                        break;
                                    case ReaderTestType.ReaderGC:
                                        switch (gcType)
                                        {
                                            case GCType.Wait:
                                                // 1 for connection, 1 for open reader
                                                Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCWait! #connections: " + connections);
                                                // only 1 executing
                                                Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCWait! #requests: " + requests);
                                                break;
                                            case GCType.NoWait:
                                                // 1 for connection, 1 for open reader
                                                Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCNoWait! #connections: " + connections);

                                                // only 1 executing
                                                Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCNoWait! #requests: " + requests);
                                                break;
                                        }
                                        break;
                                    case ReaderTestType.NoCloses:
                                        // 1 for connection, 1 for current command, 1 for 0 based array offset, plus i for open readers
                                        Assert.True(connections == (3 + i), "Failure - incorrect number of connections for NoCloses: " + connections);

                                        // 1 for current command, 1 for 0 based array offset, plus i open readers
                                        Assert.True(requests == (2 + i), "Failure - incorrect number of requests for NoCloses: " + requests);
                                        break;
                                }
                                break;
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            GCType s = (GCType)value;

            return(s == (GCType)int.Parse(parameter.ToString()));
        }
Exemplo n.º 12
0
 public ETWEventClrGCStart(GCStartTraceData gcStartTraceData) : base(gcStartTraceData)
 {
     Reason = gcStartTraceData.Reason;
     Type   = gcStartTraceData.Type;
 }
Exemplo n.º 13
0
        private static void StartProcessingEvents()
        {
            // See https://github.com/dotnet/coreclr/blob/775003a4c72f0acc37eab84628fcef541533ba4e/src/pal/prebuilt/inc/mscoree.h#L294-L315
            session.Source.Clr.RuntimeStart += runtimeData =>
            {
                if (ProcessIdsUsedInRuns.Contains(runtimeData.ProcessID) == false)
                {
                    return;
                }

                lock (ConsoleLock)
                {
                    Console.WriteLine("\nCONCURRENT_GC = {0}, SERVER_GC = {1}",
                                      (runtimeData.StartupFlags & StartupFlags.CONCURRENT_GC) == StartupFlags.CONCURRENT_GC,
                                      (runtimeData.StartupFlags & StartupFlags.SERVER_GC) == StartupFlags.SERVER_GC);
                }
            };

            session.Source.Clr.GCAllocationTick += allocationData =>
            {
                if (ProcessIdsUsedInRuns.Contains(allocationData.ProcessID) == false)
                {
                    return;
                }

                if (startTime == 0)
                {
                    startTime = allocationData.TimeStampRelativeMSec;
                }

                stopTime = allocationData.TimeStampRelativeMSec;

                totalBytesAllocated += allocationData.AllocationAmount;

                lock (ConsoleLock)
                {
                    if (allocationData.AllocationAmount > 200000)
                    {
                        Console.Write("o");
                    }
                    else
                    {
                        Console.Write(".");
                    }
                }
            };

            GCType lastGCType = 0;
            int    lastGen    = 0;
            double gcStart    = 0;

            session.Source.Clr.GCStart += startData =>
            {
                if (ProcessIdsUsedInRuns.Contains(startData.ProcessID) == false)
                {
                    return;
                }

                if (startTime == 0)
                {
                    startTime = startData.TimeStampRelativeMSec;
                }

                lastGCType = startData.Type;
                lastGen    = startData.Depth;
                gcStart    = startData.TimeStampRelativeMSec;
                IncrementGCCollectionCounts(startData);

                var colourToUse = GetColourForGC(startData.Depth);
                lock (ConsoleLock)
                {
                    if (startData.Type == GCType.ForegroundGC || startData.Type == GCType.NonConcurrentGC)
                    {
                        // Make the FG coloured/highlighted
                        Console.ForegroundColor = colourToUse;
                        Console.BackgroundColor = ConsoleColor.Black;
                    }
                    else // GCType.BackgroundGC
                    {
                        // Make the BG coloured/highlighted
                        Console.ForegroundColor = ConsoleColor.Black;
                        Console.BackgroundColor = colourToUse;
                    }

                    Console.Write(startData.Depth);
                    Console.ResetColor();
                }
            };

            session.Source.Clr.GCStop += stopData =>
            {
                if (ProcessIdsUsedInRuns.Contains(stopData.ProcessID) == false)
                {
                    return;
                }

                stopTime = stopData.TimeStampRelativeMSec;

                // If we don't have a matching start event, don't calculate the GC time
                if (gcStart == 0)
                {
                    return;
                }

                var gcTime = stopData.TimeStampRelativeMSec - gcStart;
                timeInGc += gcTime;

                lock (BinningLock)
                {
                    binning[lastGen].Add(gcTime);
                }
            };

            //In a typical blocking GC (this means all ephemeral GCs and full blocking GCs) the event sequence is very simple:
            //GCSuspendEE_V1 Event
            //GCSuspendEEEnd_V1 Event    <– suspension is done
            //GCStart_V1 Event
            //GCEnd_V1 Event             <– actual GC is done
            //GCRestartEEBegin_V1 Event
            //GCRestartEEEnd_V1 Event    <– resumption is done.

            double pauseStart = 0;

            session.Source.Clr.GCSuspendEEStop += suspendData =>
            {
                if (ProcessIdsUsedInRuns.Contains(suspendData.ProcessID) == false)
                {
                    return;
                }

                pauseStart = suspendData.TimeStampRelativeMSec;
            };

            session.Source.Clr.GCRestartEEStop += restartData =>
            {
                if (ProcessIdsUsedInRuns.Contains(restartData.ProcessID) == false)
                {
                    return;
                }

                stopTime = restartData.TimeStampRelativeMSec;

                // Only display this if the GC Type is Foreground, (Background is different!!)
                // 0x0 - NonConcurrentGC - Blocking garbage collection occurred outside background garbage collection.
                // 0x1 - BackgroundGC    - Background garbage collection.
                // 0x2 - ForegroundGC    - Blocking garbage collection occurred during background garbage collection.
                if (lastGCType == GCType.BackgroundGC)
                {
                    return;
                }

                // If we don't have a matching start event, don't calculate the "pause" time
                if (pauseStart == 0)
                {
                    return;
                }

                var pauseDurationMSec = restartData.TimeStampRelativeMSec - pauseStart;
                var pauseText         = new StringBuilder();
                while (pauseDurationMSec > 100)
                {
                    pauseText.Append('█');
                    pauseDurationMSec -= 100;
                }
                if (pauseDurationMSec > 75)
                {
                    pauseText.Append('█');
                }
                else if (pauseDurationMSec > 50)
                {
                    pauseText.Append('▓');
                }
                else if (pauseDurationMSec > 25)
                {
                    pauseText.Append('▒');
                }
                else
                {
                    pauseText.Append("░");
                }

                totalGcPauseTime += pauseDurationMSec;
                if (pauseDurationMSec > largestGcPause)
                {
                    largestGcPause = pauseDurationMSec;
                }

                lock (ConsoleLock)
                {
                    Console.ResetColor();
                    Console.Write(pauseText.ToString());
                }
            };

            session.Source.Process();
        }
Exemplo n.º 14
0
    private static (Summary, IConfig, Job)? ConditionalRun(Type benchmarkType, string[] args, Options options, GCType gcType, Runtime runtime, bool coldStart)
    {
        var config = DefaultConfig.Instance.WithOptions(ConfigOptions.Default);

        //if (Debugger.IsAttached) {
        config = config.WithOptions(ConfigOptions.DisableOptimizationsValidator);
        //}

        if (options.Runners.Count != 0)
        {
            var patterns = CreatePatterns(options.Runners);

            var filters = patterns.Select(runner =>
                                          new NameFilter(runner.IsMatch)
                                          ).Cast <IFilter>();

            var disjunction = new DisjunctionFilter(filters.ToArray());

            config = config.AddFilter(disjunction);
        }

        if (options.DiagnoseCpu)
        {
            config = config.AddDiagnoser(CpuDiagnoser.Default);
        }

        if (options.DiagnoseMemory)
        {
            config = config.AddDiagnoser(MemoryDiagnoser.Default);
        }

        if (options.DiagnoseInlining)
        {
            config = config.AddDiagnoser(new InliningDiagnoser());
        }

        if (options.DiagnoseTailCall)
        {
            config = config.AddDiagnoser(new TailCallDiagnoser());
        }

        if (options.DiagnoseEtw)
        {
            config = config.AddDiagnoser(new EtwProfiler());
        }

        //config.AddJob(Job.InProcess);

        Job job;

        if (Debugger.IsAttached || CurrentOptions.InProcess)
        {
            job = Job.InProcess
                  .WithGcServer(gcType == GCType.Server)
                  .WithRuntime(runtime)
                  .WithEnvironmentVariables(
                new EnvironmentVariable("DOTNET_TieredCompilation", "0"),
                new EnvironmentVariable("BENCHIE_ARGS", string.Join(" ", args))
                )
                  .WithStrategy(coldStart ? RunStrategy.ColdStart : RunStrategy.Throughput);
        }
        else
        {
            job = Job.Default
                  .WithGcServer(gcType == GCType.Server)
                  .WithRuntime(runtime)
                  .WithEnvironmentVariables(
                new EnvironmentVariable("DOTNET_TieredCompilation", "0"),
                new EnvironmentVariable("BENCHIE_ARGS", string.Join(" ", args))
                )
                  .WithStrategy(coldStart ? RunStrategy.ColdStart : RunStrategy.Throughput);
        }

        //if (typeof(TBenchmark) == typeof(Benchmarks.Premultiply)) {
        //	job = job.WithMinIterationCount(60).WithMaxIterationCount(400);
        //}

        string name = $"{gcType}.{runtime}.{(coldStart ? "cold" : "warm")}";

        config = config.AddJob(job);
        config = config.WithArtifactsPath(Path.Combine(config.ArtifactsPath, name));

        {
            List <Type> baseTypes = new();
            Type?       baseType  = benchmarkType;
            while (baseType is not null)
            {
                baseTypes.Add(baseType);
                baseType = baseType.BaseType;
            }

            foreach (var type in baseTypes.ReverseF())
            {
                System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
            }
        }

        GC.Collect(int.MaxValue, GCCollectionMode.Forced, blocking: true, compacting: true);

        var summary = BenchmarkRunner.Run(benchmarkType, config);

        return(summary, config, job);
    }
Exemplo n.º 15
0
 private static ((Summary, IConfig, Job)?, (Summary, IConfig, Job)?)? ConditionalRun(Type benchmarkType, string[] args, Options options, GCType gcType, Runtime runtime)
 {
     if (CurrentOptions.Cold)
     {
         return(
             ConditionalRun(benchmarkType, args, options, gcType, runtime, coldStart: true),
             ConditionalRun(benchmarkType, args, options, gcType, runtime, coldStart: false)
             );
     }
     else
     {
         return(
             null,
             ConditionalRun(benchmarkType, args, options, gcType, runtime, coldStart: false)
             );
     }
 }
Exemplo n.º 16
0
        private static void GCType_AddAdditionalMembersTo(GCType gcType, NativeNamespaceTranslator namespaceTranslator)
        {
            // This method is called through reflection when this type's corresponding GCType is populated.
            NodeTechnique method = gcType.AddDefaultNodeTechnique(NameOfDefaultTechnique, Default);

            //inputs
            method.AddArgumentDefinition(NameOfUpdateObject, typeof(Feature[]), "null", "The nodes to upadte with the timer" );
            method.AddArgumentDefinition(NameOfInterval,  typeof(double), "25", "The update time in milliseconds");
            //outputs
            method.AddArgumentDefinition(NameOfReset, typeof(bool), "true", "The reset state (true/false)", NodePortRole.TechniqueOutputOnly);
            method.AddArgumentDefinition(NameOfFrame, typeof(int), "0", "The current frame", NodePortRole.TechniqueOutputOnly);
        }
Exemplo n.º 17
0
        private static void TestMARSSessionPooling(string caseName, string connectionString, CommandType commandType,
                                                   ExecuteType executeType, ReaderTestType readerTestType, GCType gcType)
        {
            SqlCommand[]    cmd = new SqlCommand[CONCURRENT_COMMANDS];
            SqlDataReader[] gch = new SqlDataReader[CONCURRENT_COMMANDS];

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                con.Open();

                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
                {
                    // Prepare all commands
                    cmd[i] = con.CreateCommand();
                    switch (commandType)
                    {
                    case CommandType.Text:
                        cmd[i].CommandText    = _COMMAND_SQL;
                        cmd[i].CommandTimeout = 120;
                        break;

                    case CommandType.StoredProcedure:
                        cmd[i].CommandText    = _COMMAND_RPC;
                        cmd[i].CommandTimeout = 120;
                        cmd[i].CommandType    = CommandType.StoredProcedure;
                        break;
                    }
                }

                for (int i = 0; i < CONCURRENT_COMMANDS; i++)
                {
                    switch (executeType)
                    {
                    case ExecuteType.ExecuteScalar:
                        cmd[i].ExecuteScalar();
                        break;

                    case ExecuteType.ExecuteNonQuery:
                        cmd[i].ExecuteNonQuery();
                        break;

                    case ExecuteType.ExecuteReader:
                        if (readerTestType != ReaderTestType.ReaderGC)
                        {
                            gch[i] = cmd[i].ExecuteReader();
                        }

                        switch (readerTestType)
                        {
                        case ReaderTestType.ReaderClose:
                        {
                            gch[i].Dispose();
                            break;
                        }

                        case ReaderTestType.ReaderDispose:
                            gch[i].Dispose();
                            break;

                        case ReaderTestType.ReaderGC:
                            gch[i] = null;
                            WeakReference weak = OpenReaderThenNullify(cmd[i]);
                            GC.Collect();

                            if (gcType == GCType.Wait)
                            {
                                GC.WaitForPendingFinalizers();
                                Assert.False(weak.IsAlive, "Error - target still alive!");
                            }
                            break;

                        case ReaderTestType.ConnectionClose:
                            GC.SuppressFinalize(gch[i]);
                            con.Close();
                            con.Open();
                            break;

                        case ReaderTestType.NoCloses:
                            GC.SuppressFinalize(gch[i]);
                            break;
                        }
                        break;
                    }

                    if (readerTestType != ReaderTestType.NoCloses)
                    {
                        con.Close();
                        con.Open(); // Close and open, to re-assure collection!
                    }

                    using (SqlCommand verificationCmd = con.CreateCommand())
                    {
                        verificationCmd.CommandText = COMMAND_STATUS;
                        using (SqlDataReader rdr = verificationCmd.ExecuteReader())
                        {
                            rdr.Read();
                            int connections = (int)rdr.GetValue(0);
                            int spid1       = (Int16)rdr.GetValue(1);
                            rdr.NextResult();
                            rdr.Read();
                            int requests = (int)rdr.GetValue(0);
                            int spid2    = (Int16)rdr.GetValue(1);

                            switch (executeType)
                            {
                            case ExecuteType.ExecuteScalar:
                            case ExecuteType.ExecuteNonQuery:
                                // 1 for connection, 1 for command
                                Assert.True(connections == 2, "Failure - incorrect number of connections for ExecuteScalar! #connections: " + connections);

                                // only 1 executing
                                Assert.True(requests == 1, "Failure - incorrect number of requests for ExecuteScalar! #requests: " + requests);
                                break;

                            case ExecuteType.ExecuteReader:
                                switch (readerTestType)
                                {
                                case ReaderTestType.ReaderClose:
                                case ReaderTestType.ReaderDispose:
                                case ReaderTestType.ConnectionClose:
                                    // 1 for connection, 1 for command
                                    Assert.True(connections == 2, "Failure - Incorrect number of connections for ReaderClose / ReaderDispose / ConnectionClose! #connections: " + connections);

                                    // only 1 executing
                                    Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderClose/ReaderDispose/ConnectionClose! #requests: " + requests);
                                    break;

                                case ReaderTestType.ReaderGC:
                                    switch (gcType)
                                    {
                                    case GCType.Wait:
                                        // 1 for connection, 1 for open reader
                                        Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCWait! #connections: " + connections);
                                        // only 1 executing
                                        Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCWait! #requests: " + requests);
                                        break;

                                    case GCType.NoWait:
                                        // 1 for connection, 1 for open reader
                                        Assert.True(connections == 2, "Failure - incorrect number of connections for ReaderGCNoWait! #connections: " + connections);

                                        // only 1 executing
                                        Assert.True(requests == 1, "Failure - incorrect number of requests for ReaderGCNoWait! #requests: " + requests);
                                        break;
                                    }
                                    break;

                                case ReaderTestType.NoCloses:
                                    // 1 for connection, 1 for current command, 1 for 0 based array offset, plus i for open readers
                                    Assert.True(connections == (3 + i), "Failure - incorrect number of connections for NoCloses: " + connections +
                                                "\ni: " + i + " :::: requests: " + requests + " :::: spid1: " + spid1 + " ::::: spid2: " + spid2);

                                    // 1 for current command, 1 for 0 based array offset, plus i open readers
                                    Assert.True(requests == (2 + i), "Failure - incorrect number of requests for NoCloses: " + requests +
                                                "\ni: " + i + " :::: connections: " + connections + " :::: spid1: " + spid1 + " ::::: spid2: " + spid2);
                                    break;
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 18
0
 public static void GCRequest(int gen = -1, GCType type = GCType.GCOptimized)
 {
     GCWorker._GCRequested = true;
     GCWorker._GCGen       = gen;
     GCWorker._GCType      = type;
 }