private static void MonitorSensor(string sensorId, CancellationToken cancellationToken) { var sequenceNo = 0; while (!cancellationToken.IsCancellationRequested) { using (var db = new BloggingContext()) { var data = CreateSomeFakeSensorReads(sensorId, sequenceNo, 100); sequenceNo += 100; using (var transaction = db.Database.BeginTransaction()) { db.SensorReads.AddRange(data); db.SaveChanges(); var ids = data.Select(s => s.SequenceNo).ToArray(); ; db.SensorReads .AsNoTracking() .OrderByDescending(s => s.SequenceNo) .Where(c => c.SensorId == sensorId && ids.Contains(c.SequenceNo)) .ToList(); transaction.Commit(); } } } }
private static void SetupDatabase() { using (var db = new BloggingContext()) { Console.WriteLine("Dropping the database"); db.Database.EnsureDeleted(); Console.WriteLine("Creating the database"); db.Database.EnsureCreated(); } }
private static void MonitorDatabase(object threadParams) { var ct = (CancellationToken)threadParams; using (var db = new BloggingContext()) { var cmd = db.Database.GetDbConnection().CreateCommand(); cmd.CommandText = "select max(cntr_value) FROM sys.dm_os_performance_counters WHERE counter_name = 'Batch Requests/sec'"; db.Database.OpenConnection(); var firstValue = (long)cmd.ExecuteScalar(); var firstRead = DateTime.Now; Thread.Sleep(3000); while (!ct.IsCancellationRequested) { var thisValue = (long)cmd.ExecuteScalar(); var thisRead = DateTime.Now; var totalRequests = thisValue - firstValue; var requestsPerSecond = totalRequests / (thisRead - firstRead).TotalSeconds; Console.WriteLine($"Average: {requestsPerSecond:0} requests/sec ({totalRequests} total requests)"); Thread.Sleep(3000); } db.Database.CloseConnection(); } }