/// <summary> /// Initializes a new instance of the <see cref="ConcurrencyModeAttribute"/> class. /// </summary> /// <param name="concurrencyMode">The concurrency mode.</param> public ConcurrencyModeAttribute(ConcurrencyMode concurrencyMode) { using (Logger.Assembly.Scope()) { ConcurrencyMode = concurrencyMode; } }
internal void Open(ConcurrencyMode concurrency) { _concurrency = concurrency; //Action open = delegate { try { if (_host == null) { RpcExecuteHandler onExecute = delegate(IRpcCallInfo client, byte[] arg) { if (_concurrency == ConcurrencyMode.Single) { //lock (this) //{ _operationPending.Reset(); try { return Invoke(client, _endpoint._contractType, arg); } finally { _operationPending.Set(); } //} } if (_concurrency == ConcurrencyMode.Multiple) { //BUG: need have collection of operations because second operation rewrites state of first _operationPending.Reset(); try { return Invoke(client, _endpoint._contractType, arg); } finally { _operationPending.Set(); } } throw new NotImplementedException( string.Format("ConcurrencyMode {0} is note implemented", _concurrency)); }; _host = RpcRequestReplyChannelFactory.CreateHost(_endpoint._binding, _endpoint._address, _endpoint._uuid); _host.OnExecute += onExecute; _host.StartListening(); } //_opened.Set(); } catch (Exception ex) { bool handled = ExceptionHandler.AlwaysHandle.HandleException(ex); if (!handled) throw; } }; //Tasks.Factory.StartNew(open); //_opened.WaitOne(); }
public static bool IsDefined(ConcurrencyMode x) { if ((x != ConcurrencyMode.Single) && (x != ConcurrencyMode.Reentrant)) { return (x == ConcurrencyMode.Multiple); } return true; }
static public bool IsDefined(ConcurrencyMode x) { return x == ConcurrencyMode.Single || x == ConcurrencyMode.Reentrant || x == ConcurrencyMode.Multiple || false; }
public CBAProgram(Program p, string main, int bound) : base() { tok = p.tok; TopLevelDeclarations = p.TopLevelDeclarations; mainProcName = main; contextBound = bound; mode = ConcurrencyMode.AnyInterleaving; }
public static void AddConcurrencyMode(this ServiceHostBase host, ConcurrencyMode mode) { ServiceHostData data = GetServiceHostData(host); if (data != null) { data.ServiceConcurrencyMode = mode; } }
private void runToolStripMenuItem_Click(object sender, EventArgs e) { fractalToolStripMenuItem.Enabled = false; modeToolStripMenuItem.Enabled = false; viewToolStripMenuItem.Enabled = false; benchmarkingToolStripMenuItem.Enabled = false; reportToolStripMenuItem.Enabled = false; Size[] sizes = new Size[] { new Size(320, 240), new Size(640, 480), new Size(800, 600), new Size(1024, 768) }; ConcurrencyMode[] modes = new ConcurrencyMode[] { ConcurrencyMode.SequentialCPU, ConcurrencyMode.ParallelCPU, ConcurrencyMode.GPU }; FractalGenerator[] generators = new FractalGenerator[] { new Julia(), new Mandelbrot() }; this.metrics.Clear(); foreach (Size size in sizes) { this.SetResolution(size.Width, size.Height); foreach (ConcurrencyMode mode in modes) { this.SetConcurrencyMode(mode); foreach (FractalGenerator generator in generators) { this.SetCurrentGenerator(generator); this.Draw(); } } } fractalToolStripMenuItem.Enabled = true; modeToolStripMenuItem.Enabled = true; viewToolStripMenuItem.Enabled = true; benchmarkingToolStripMenuItem.Enabled = true; reportToolStripMenuItem.Enabled = true; GenerationMetricChartForm chartForm = new GenerationMetricChartForm(); chartForm.LoadMetrics(this.metrics); chartForm.ShowDialog(this); }
public CBAProgram(Program p, string main, int bound, ConcurrencyMode mode) : base() { tok = p.tok; TopLevelDeclarations = p.TopLevelDeclarations; mainProcName = main; contextBound = bound; this.mode = mode; }
public ServiceConfigurationAttribute(string behaviorConfiguration, bool customErrorHandler, TransferMode transferMode, InstanceContextMode instanceContextMode, ConcurrencyMode concurencyMode, params string[] bindingConfiguration) { InstanceContextMode = instanceContextMode; ConcurrencyMode = concurencyMode; CustomErrorHandler = customErrorHandler; TransferMode = transferMode; BehaviorConfiguration = behaviorConfiguration; BindingConfiguration = bindingConfiguration; }
public ServiceConfigurationAttribute(string behaviorConfiguration, bool customErrorHandler, TransferMode transferMode, InstanceContextMode instanceContextMode, ConcurrencyMode concurencyMode, params string[] bindingConfiguration) { InstanceContextMode = instanceContextMode; ConcurrencyMode = concurencyMode; CustomErrorHandler = customErrorHandler; TransferMode = transferMode; BehaviorConfiguration = behaviorConfiguration; BindingConfiguration = bindingConfiguration; }
public async Task TrySaveStateAsync_ValidateOptions( ConsistencyMode consistencyMode, ConcurrencyMode concurrencyMode, StateConsistency expectedConsistency, StateConcurrency expectedConcurrency) { // Configure Client var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient }) .Build(); var widget = new Widget() { Size = "small", Color = "yellow", }; var stateOptions = new StateOptions { Concurrency = concurrencyMode, Consistency = consistencyMode }; var metadata = new Dictionary <string, string> { { "key1", "value1" }, { "key2", "value2" } }; var task = daprClient.TrySaveStateAsync("testStore", "test", widget, "Test_Etag", stateOptions, metadata); // Get Request and validate httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); var request = await GrpcUtils.GetRequestFromRequestMessageAsync <Autogenerated.SaveStateRequest>(entry.Request); request.StoreName.Should().Be("testStore"); request.States.Count.Should().Be(1); var state = request.States[0]; state.Key.Should().Be("test"); state.Etag.Should().Be("Test_Etag"); state.Metadata.Count.Should().Be(2); state.Metadata.Keys.Contains("key1").Should().BeTrue(); state.Metadata.Keys.Contains("key2").Should().BeTrue(); state.Metadata["key1"].Should().Be("value1"); state.Metadata["key2"].Should().Be("value2"); state.Options.Concurrency.Should().Be(expectedConcurrency); state.Options.Consistency.Should().Be(expectedConsistency); var stateJson = state.Value.ToStringUtf8(); var stateFromRequest = JsonSerializer.Deserialize <Widget>(stateJson); stateFromRequest.Size.Should().Be(widget.Size); stateFromRequest.Color.Should().Be(widget.Color); }
public async Task SaveStateAsync_ValidateOptions( ConsistencyMode consistencyMode, ConcurrencyMode concurrencyMode, StateConsistency expectedConsistency, StateConcurrency expectedConcurrency) { await using var client = TestClient.CreateForDaprClient(); var widget = new Widget() { Size = "small", Color = "yellow", }; var stateOptions = new StateOptions { Concurrency = concurrencyMode, Consistency = consistencyMode }; var metadata = new Dictionary <string, string> { { "key1", "value1" }, { "key2", "value2" } }; var request = await client.CaptureGrpcRequestAsync(async daprClient => { await daprClient.SaveStateAsync("testStore", "test", widget, stateOptions, metadata); }); request.Dismiss(); // Get Request and validate var envelope = await request.GetRequestEnvelopeAsync <Autogenerated.SaveStateRequest>(); envelope.StoreName.Should().Be("testStore"); envelope.States.Count.Should().Be(1); var state = envelope.States[0]; state.Key.Should().Be("test"); state.Metadata.Count.Should().Be(2); state.Metadata.Keys.Contains("key1").Should().BeTrue(); state.Metadata.Keys.Contains("key2").Should().BeTrue(); state.Metadata["key1"].Should().Be("value1"); state.Metadata["key2"].Should().Be("value2"); state.Options.Concurrency.Should().Be(expectedConcurrency); state.Options.Consistency.Should().Be(expectedConsistency); var stateJson = state.Value.ToStringUtf8(); var stateFromRequest = JsonSerializer.Deserialize <Widget>(stateJson, client.InnerClient.JsonSerializerOptions); stateFromRequest.Size.Should().Be(widget.Size); stateFromRequest.Color.Should().Be(widget.Color); }
// Determines whether the given member is declared as a concurrency property internal static ConcurrencyMode GetConcurrencyMode(TypeUsage typeUsage) { Facet concurrencyFacet; if (typeUsage.Facets.TryGetValue(EdmProviderManifest.ConcurrencyModeFacetName, false, out concurrencyFacet) && concurrencyFacet.Value != null) { ConcurrencyMode concurrencyMode = (ConcurrencyMode)concurrencyFacet.Value; return(concurrencyMode); } return(ConcurrencyMode.None); }
public RedisSagaRepositoryOptions(ConcurrencyMode concurrencyMode, TimeSpan?lockTimeout, string lockSuffix, string keyPrefix) { ConcurrencyMode = concurrencyMode; LockTimeout = lockTimeout ?? TimeSpan.FromSeconds(30); LockSuffix = string.IsNullOrEmpty(lockSuffix) ? "_lock" : lockSuffix; KeyPrefix = string.IsNullOrWhiteSpace(keyPrefix) ? null : keyPrefix.EndsWith(":") ? keyPrefix : $"{keyPrefix}:"; RetryPolicy = Retry.Exponential(10, TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(10), TimeSpan.FromMilliseconds(918)); }
internal static bool IsConcurrent(ConcurrencyMode mode, bool hasSession, bool supportsTransactedBatch) { if (supportsTransactedBatch) { return(false); } if (mode == ConcurrencyMode.Single) { return(!hasSession); } return(true); }
/// <summary> /// 向工作单元中提交一个删除实体的请求(支持并发冲突检查) /// </summary> /// <param name="entity"></param> /// <param name="concurrencyMode"></param> public void Delete(BaseEntity entity, ConcurrencyMode concurrencyMode) { if (entity == null) { throw new ArgumentNullException("entity"); } int flag = concurrencyMode == ConcurrencyMode.TimeStamp ? 5 : 6; CPQuery query = entity.GetCPQuery(flag, entity); AddExecuteOjbect(query, true, entity.FuncBefore); }
internal static bool IsConcurrent(ConcurrencyMode mode, bool hasSession, bool supportsTransactedBatch) { if (supportsTransactedBatch) { return false; } if (mode == ConcurrencyMode.Single) { return !hasSession; } return true; }
/// <summary> /// Initializes a new instance of the <see cref="GenerationMetric"/> /// class. /// </summary> /// <param name="type">The type of fractal generated.</param> /// <param name="mode">The ConcurrencyMode used to generate the image.</param> /// <param name="width">The width of the generated image.</param> /// <param name="height">The height of the generated image.</param> /// <param name="milliseconds">The milliseconds required to generate the image.</param> public GenerationMetric(string type, ConcurrencyMode mode, int width, int height, double milliseconds) { this.type = type; this.mode = mode; this.width = width; this.height = height; this.milliseconds = milliseconds; }
public InstrumentationPolicy(int K, HashSet <string> glob, HashSet <string> procsWithImpl, HashSet <string> asyncProcs, HashSet <Tuple <string, string> > recursiveProcs, ConcurrencyMode mode) { executionContextBound = K; globalsToInstrument = glob; this.procsWithImpl = procsWithImpl; this.asyncProcs = asyncProcs; this.recursiveProcs = recursiveProcs; this.mode = mode; atomicBeginProcName = LanguageSemantics.atomicBeginProcName(); atomicEndProcName = LanguageSemantics.atomicEndProcName(); assertNotReachableName = LanguageSemantics.assertNotReachableName(); getThreadIDName = LanguageSemantics.getThreadIDName(); }
// ReSharper restore PossibleMultipleEnumeration // ReSharper disable PossibleMultipleEnumeration /// <summary> /// Initializes a new instance of the <see cref="ConcurrencyConflictException"/> class. /// </summary> /// <param name="entityDataType">Type of the entity data.</param> /// <param name="concurrencyMode">The concurrency mode.</param> /// <param name="conflictingPropertyNames">The conflicting property names.</param> public ConcurrencyConflictException(Type entityDataType, ConcurrencyMode concurrencyMode, IEnumerable<string> conflictingPropertyNames = null) : base(string.Format(ERROR_MESSAGE_FORMAT, entityDataType, concurrencyMode, (conflictingPropertyNames == null) ? "" : string.Join(", ", conflictingPropertyNames))) { using (Logger.Assembly.Scope()) { EntityDataType = entityDataType; ConcurrencyMode = concurrencyMode; // ReSharper disable PossibleMultipleEnumeration ConflictingPropertyNames = conflictingPropertyNames; // ReSharper restore PossibleMultipleEnumeration } }
public static IResponsiveClient GetRunningToolkitTypeHelper(ConcurrencyMode mode) { if (config == null) { config = ClientConfiguration.GetInstance(); Console.Out.WriteLine(config.GuiToolkit); } if (config.GuiToolkit == "WinForms") { return new WinFormsResponsiveHelper(mode); } else { return new ConsoleResponsiveHelper(mode); } }
public virtual int Delete(ConcurrencyMode concurrencyMode) { int flag = (concurrencyMode == ConcurrencyMode.TimeStamp) ? 5 : 6; CPQuery cPQuery = this.GetCPQuery(flag, new object[] { this }); if ((this._funcBefore != null) && !this._funcBefore(cPQuery)) { return(-1); } int num2 = cPQuery.ExecuteNonQuery(); if (num2 == 0) { throw new OptimisticConcurrencyException("并发操作失败,本次操作没有删除任何记录,请确认当前数据行没有被其他用户更新或删除。"); } return(num2); }
internal SingleItemNonOverlappedDiscountResult( DiscountOfferMethod discountMethod, decimal discountAmount, decimal discountPercentage, decimal offerPrice, decimal unitDiscountAmount, ConcurrencyMode concurrencyMode) : this( discountMethod, discountAmount, discountPercentage, offerPrice, unitDiscountAmount, concurrencyMode, isIndependentOfOverlappedDiscounts : true) { }
/// <summary> /// 向工作单元中提交一个更新实体的请求(支持并发冲突检查) /// </summary> /// <param name="entity"></param> /// <param name="original">用于并发检测的原始对象</param> /// <param name="concurrencyMode"></param> public void Update(BaseEntity entity, BaseEntity original, ConcurrencyMode concurrencyMode) { if (entity == null) { throw new ArgumentNullException("entity"); } if (concurrencyMode == ConcurrencyMode.OriginalValue && object.ReferenceEquals(entity, original)) { throw new ArgumentException("用于并发检测的原始对象不能是当前对象。"); } int flag = concurrencyMode == ConcurrencyMode.TimeStamp ? 8 : 9; CPQuery query = entity.GetCPQuery(flag, entity, original, entity.bakObject); AddExecuteOjbect(query, true, entity.FuncBefore); }
internal SingleItemNonOverlappedDiscountResult( DiscountOfferMethod discountMethod, decimal discountAmount, decimal discountPercentage, decimal offerPrice, decimal unitDiscountAmount, ConcurrencyMode concurrencyMode, bool isIndependentOfOverlappedDiscounts) : this(true) { this.DiscountMethod = discountMethod; this.DiscountAmount = discountAmount; this.DiscountPercentage = discountPercentage; this.OfferPrice = offerPrice; this.UnitDiscountAmount = unitDiscountAmount; this.CanCompound = concurrencyMode == ConcurrencyMode.Compounded; this.IsIndependentOfOverlappedDiscounts = isIndependentOfOverlappedDiscounts; }
internal static bool IsConcurrent(ConcurrencyMode concurrencyMode, bool ensureOrderedDispatch, bool hasSession) { if (concurrencyMode != ConcurrencyMode.Single) { return true; } if (hasSession) { return false; } if (ensureOrderedDispatch) { return false; } return true; }
public async Task TryDeleteStateAsync_ValidateOptions( ConsistencyMode consistencyMode, ConcurrencyMode concurrencyMode, RetryMode retryMode, StateConsistency expectedConsistency, StateConcurrency expectedConcurrency, RetryPattern expectedRetryMode) { // Configure Client var httpClient = new TestHttpClient(); var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { HttpClient = httpClient }) .Build(); var stateOptions = new StateOptions { Concurrency = concurrencyMode, Consistency = consistencyMode, RetryOptions = new RetryOptions { RetryInterval = TimeSpan.FromSeconds(5), RetryMode = retryMode, RetryThreshold = 10 } }; var task = daprClient.TryDeleteStateAsync("testStore", "test", "Test_Etag", stateOptions); // Get Request and validate httpClient.Requests.TryDequeue(out var entry).Should().BeTrue(); var request = await GrpcUtils.GetRequestFromRequestMessageAsync <Autogenerated.DeleteStateRequest>(entry.Request); request.StoreName.Should().Be("testStore"); request.Key.Should().Be("test"); request.Etag.Should().Be("Test_Etag"); request.Options.Concurrency.Should().Be(expectedConcurrency); request.Options.Consistency.Should().Be(expectedConsistency); request.Options.RetryPolicy.Pattern.Should().Be(expectedRetryMode); request.Options.RetryPolicy.Threshold.Should().Be(10); request.Options.RetryPolicy.Interval.Seconds.Should().Be(5); }
internal static bool IsConcurrent(ConcurrencyMode concurrencyMode, bool ensureOrderedDispatch, bool hasSession) { if (concurrencyMode != ConcurrencyMode.Single) { return(true); } if (hasSession) { return(false); } if (ensureOrderedDispatch) { return(false); } return(true); }
// effects: Returns all the concurrency token members in superType and its subtypes internal static Set <EdmMember> GetConcurrencyMembersForTypeHierarchy(EntityTypeBase superType, EdmItemCollection edmItemCollection) { Set <EdmMember> result = new Set <EdmMember>(); foreach (StructuralType type in GetTypeAndSubtypesOf(superType, edmItemCollection, true /*includeAbstractTypes */)) { // Go through all the members -- Can call Members instead of AllMembers since we are // running through the whole hierarchy foreach (EdmMember member in type.Members) { // check for the concurrency facet ConcurrencyMode concurrencyMode = GetConcurrencyMode(member); if (concurrencyMode == ConcurrencyMode.Fixed) { result.Add(member); } } } return(result); }
/// <summary> /// 用并发检测的方式,更新数据实体对应的记录。 /// </summary> /// <example> /// <para>下面的代码演示了并发检测模式下,Update()方法的用法</para> /// <code> /// <![CDATA[ /// //Contract类需要继承自BaseEntity,并且需要放在以*.Entity.dll结尾的程序集中 /// /// public void Load(){ /// /// //在页面加载时,查询数据库信息,时间戳字段需要通过CAST转换为长整型,绑定到界面中 /// Contract contract = CPQuery.From("SELECT ContractGUID, CAST(ContractVersion AS BigInt) ContractVersion .... FROM cb_Contract WHERE ...").ToSingle<Contract>(); /// /// //其他数据绑定代码 /// //... /// } /// /// public void Update(string dataXML, long contractVersion){ /// //将AppFrom的xml直接转换为实体对象 /// Contract contract = XmlDataEntity.ConvertXmlToSingle<CbContract>(dataXML) /// /// //构造用于并发检测的原对象 /// Contract origContract = new Contract(); /// origContract.ContractGUID = contract.ContractGUID; //并发检测时,原对象的主键是必须提供的 /// contract.ContractVersion = contractVersion.Int64ToTimeStamp(); //界面中长整型的时间戳字段可以通过Int64ToTimeStamp扩展方法转换为byte[]数组 /// /// try{ /// //根据时间戳字段,进行并发检测 /// int count = contract.Update(origContract, ConcurrencyMode.TimeStamp); /// //如果更新成功,则count为1 /// /// //根据原始值,进行并发检测 /// //count = contract.Update(origContract, ConcurrencyMode.OriginalValue); /// } /// catch(OptimisticConcurrencyException ex){ /// //并发检测失败,将会抛出OptimisticConcurrencyException异常 /// } /// } /// ]]> /// </code> /// </example> /// <param name="original">用于并发检测的原始对象</param> /// <param name="concurrencyMode">并发检测模式</param> /// <exception cref="InvalidProgramException">如果数据实体类型的定义不符合规范,就会抛出此异常</exception> /// <exception cref="InvalidOperationException">类没有定义主键,即没有任何一个属性被标记为PrimaryKey=true,则抛出此异常</exception> /// <exception cref="ArgumentException">用于并发检测的原始对象不能是当前对象</exception> /// <exception cref="Panto.Map.Extensions.Exception.OptimisticConcurrencyException">并发检测失败时,则会抛出此异常</exception> /// <returns>返回ADO.NET的原始结果</returns> public virtual int Update(BaseEntity original, ConcurrencyMode concurrencyMode) { if (original == null) { throw new ArgumentNullException("original"); } if (concurrencyMode == ConcurrencyMode.OriginalValue && object.ReferenceEquals(this, original)) { throw new ArgumentException("用于并发检测的原始对象不能是当前对象。"); } int flag = concurrencyMode == ConcurrencyMode.TimeStamp ? 8 : 9; CPQuery query = GetCPQuery(flag, new object[] { this, original, bakObject }); Valid(_ignoreValidField); if (query == null) { return(0); } if (_funcBefore != null) { if (_funcBefore(query) == false) { return(-1); } } int effectRows = query.ExecuteNonQuery(); if (effectRows == 0) { throw new Panto.Map.Extensions.Exception.OptimisticConcurrencyException( "并发操作失败,本次操作没有更新任何记录,请确认当前数据行没有被其他用户更新或删除。"); } return(effectRows); }
private void ConcurrencyDelete(ConcurrencyMode concurrencyMode) { // 注意:为了方便设计代码生成, t1 为当前对象,t2 则为参考对象。 _sb.AppendFormat("public static CPQuery ConcurrencyDelete_{1}({0} t2) {{\r\n", _entityType.FullName, concurrencyMode.ToString()); if (concurrencyMode == ConcurrencyMode.TimeStamp && IsTimeStampFieldNotExist()) { return; } if (EnsureExistPrimaryField("删除")) { return; } //CheckPrimaryKeyValue("t1"); CheckPrimaryKeyValue("t2"); if (concurrencyMode == ConcurrencyMode.OriginalValue) { _sb.AppendFormat("{0} t1 = s_Empty;\r\n", _entityType.FullName); } //_sb.AppendFormat("CPQuery query = CPQuery.Create() + \"delete from [{0}] \"; \r\n", _tableInfo.DbName); _sb.AppendFormat("CPQuery query = CPQuery.Create() + \"delete from {0} \"; \r\n", _tableInfo.DbName); if (concurrencyMode == ConcurrencyMode.TimeStamp) { _sb.AppendLine("WhereByTimeStamp(query, t2);"); } else { _sb.AppendLine("WhereByOriginalValue(query, t1, t2);"); } _sb.AppendLine("return query;"); _sb.AppendLine("}"); }
public void ValidateRuntime() { if (!this.validated) { Fx.Assert( OperationContext.Current != null && OperationContext.Current.EndpointDispatcher != null && OperationContext.Current.EndpointDispatcher.DispatchRuntime != null, "There shouldn't have been a null value in " + "OperationContext.Current.EndpointDispatcher.DispatchRuntime."); this.concurrencyMode = OperationContext.Current.EndpointDispatcher.DispatchRuntime.ConcurrencyMode; if (this.concurrencyMode == ConcurrencyMode.Multiple) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR2.GetString(SR2.ConcurrencyMultipleNotSupported))); } if (this.saveStateInOperationTransaction && this.concurrencyMode != ConcurrencyMode.Single) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR2.GetString(SR2.SaveStateInTransactionRequiresSingle))); } if (this.concurrencyMode == ConcurrencyMode.Reentrant && this.exceptionAction == UnknownExceptionAction.AbortInstance) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR2.GetString(SR2.ConcurrencyReentrantAndAbortNotSupported))); } this.validated = true; } }
public void ValidateRuntime() { if (!this.validated) { Fx.Assert( OperationContext.Current != null && OperationContext.Current.EndpointDispatcher != null && OperationContext.Current.EndpointDispatcher.DispatchRuntime != null, "There shouldn't have been a null value in " + "OperationContext.Current.EndpointDispatcher.DispatchRuntime."); this.concurrencyMode = OperationContext.Current.EndpointDispatcher.DispatchRuntime.ConcurrencyMode; if (this.concurrencyMode == ConcurrencyMode.Multiple) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR2.GetString(SR2.ConcurrencyMultipleNotSupported))); } if (this.saveStateInOperationTransaction && this.concurrencyMode != ConcurrencyMode.Single) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR2.GetString(SR2.SaveStateInTransactionRequiresSingle))); } if (this.concurrencyMode == ConcurrencyMode.Reentrant && this.exceptionAction == UnknownExceptionAction.AbortInstance) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new InvalidOperationException( SR2.GetString(SR2.ConcurrencyReentrantAndAbortNotSupported))); } this.validated = true; } }
/// <summary> /// 用并发检测的方式,将数据实体对应的记录从数据库表中删除。 /// </summary> /// <example> /// <para>下面的代码演示了并发检测模式下,Delete()方法的用法</para> /// <code> /// <![CDATA[ /// //Contract类需要继承自BaseEntity,并且需要放在以*.Entity.dll结尾的程序集中 /// /// public void Load(){ /// /// //在页面加载时,查询数据库信息,时间戳字段需要通过CAST转换为长整型,绑定到界面中 /// Contract contract = CPQuery.From("SELECT ContractGUID, CAST(ContractVersion AS BigInt) ContractVersion .... FROM cb_Contract WHERE ...").ToSingle<Contract>(); /// /// //其他数据绑定代码 /// //... /// } /// /// //删除通道,前端需要传递合同GUID,时间戳字段 /// public void Delete(Guid contractGUID, long contractVersion){ /// /// //删除动作,需要构建一个实体对象 /// Contract contract = new Contract(); /// contract.ContractGUID = contractGUID; //主键必须赋值,这是删除语句的首要条件 /// contract.ContractVersion = contractVersion.Int64ToTimeStamp(); //界面中长整型的时间戳字段可以通过Int64ToTimeStamp扩展方法转换为byte[]数组 /// /// try{ /// //根据时间戳字段,进行并发检测 /// int count = contract.Delete(ConcurrencyMode.TimeStamp); /// //如果删除成功,则count为1 /// /// //根据原始值,进行并发检测 /// //count = contract.Delete(oldContract, ConcurrencyMode.OriginalValue); /// } /// catch(OptimisticConcurrencyException ex){ /// //并发检测失败,将会抛出OptimisticConcurrencyException异常 /// } /// } /// ]]> /// </code> /// </example> /// <exception cref="InvalidProgramException">如果数据实体类型的定义不符合规范,就会抛出此异常</exception> /// <exception cref="InvalidOperationException">类没有定义主键,即没有任何一个属性被标记为PrimaryKey=true,则抛出此异常</exception> /// <exception cref="Citms.Data.Extensions.Exception.OptimisticConcurrencyException">并发检测失败时,则会抛出此异常</exception> /// <param name="concurrencyMode">并发检测模式</param> /// <param name="connectionString">数据库连接字符串,默认值为null 即表示使用默认连接字符串</param> /// <returns>返回ADO.NET的原始结果</returns> public virtual int Delete(ConcurrencyMode concurrencyMode, string connectionString = null) { int flag = concurrencyMode == ConcurrencyMode.TimeStamp ? 5 : 6; CPQuery query = GetCPQuery(flag, new object[] { this, connectionString }); if (_funcBefore != null) { if (_funcBefore(query) == false) { return(-1); } } int effectRows = query.ExecuteNonQuery(); if (effectRows == 0) { throw new OptimisticConcurrencyException( "并发操作失败,本次操作没有删除任何记录,请确认当前数据行没有被其他用户更新或删除。"); } return(effectRows); }
/// <summary> /// Toggles the concurrency mode. /// </summary> private void SetConcurrencyMode(ConcurrencyMode mode) { this.concurrencyMode = mode; this.parallelToolStripMenuItem.Checked = false; this.sequentialToolStripMenuItem.Checked = false; this.gPUToolStripMenuItem.Checked = false; if (this.concurrencyMode == ConcurrencyMode.ParallelCPU) { this.parallelToolStripMenuItem.Checked = true; } else if (this.concurrencyMode == ConcurrencyMode.SequentialCPU) { this.sequentialToolStripMenuItem.Checked = true; } else if (this.concurrencyMode == ConcurrencyMode.GPU) { this.gPUToolStripMenuItem.Checked = true; } }
internal static bool IsConcurrent(ConcurrencyMode concurrencyMode, bool ensureOrderedDispatch, bool hasSession /*, bool supportsTransactedBatch*/) { //if (supportsTransactedBatch) //{ // return false; //} if (concurrencyMode != ConcurrencyMode.Single) { return(true); } if (hasSession) { return(false); } if (ensureOrderedDispatch) { return(false); } return(true); }
protected ScanStrategy(ConcurrencyMode concurrency) { _concurrency = concurrency; _nextInstance = new WeakReference(null, false); }
internal ConcurrencyBehavior(DispatchRuntime runtime) { this.mode = runtime.ConcurrencyMode; this.supportsTransactedBatch = SupportsTransactedBatch(runtime.ChannelDispatcher); }
internal ConcurrencyBehavior(DispatchRuntime runtime) { _concurrencyMode = runtime.ConcurrencyMode; _enforceOrderedReceive = runtime.EnsureOrderedDispatch; }
public static IHost ConcurrencyMode(this IHost me, ConcurrencyMode mode) { (me as _Host).ServiceHost.Description.Behaviors.Find <ServiceBehaviorAttribute>().ConcurrencyMode = mode; return(me); }
internal ConcurrencyBehavior(DispatchRuntime runtime) { this.concurrencyMode = runtime.ConcurrencyMode; this.enforceOrderedReceive = runtime.EnsureOrderedDispatch; this.supportsTransactedBatch = ConcurrencyBehavior.SupportsTransactedBatch(runtime.ChannelDispatcher); }
protected AbstractResponsiveHelper(ConcurrencyMode mode) { _concurrencyMode = mode; _innerLock = _threadDictionariesList; }
internal ConcurrencyBehavior(DispatchRuntime runtime) { concurrencyMode = runtime.ConcurrencyMode; enforceOrderedReceive = runtime.EnsureOrderedDispatch; //this.supportsTransactedBatch = ConcurrencyBehavior.SupportsTransactedBatch(runtime.ChannelDispatcher); }
internal void Open(ConcurrencyMode concurrency) { _concurrency = concurrency; //Action open = delegate { try { if (_host == null) { RpcExecuteHandler onExecute = delegate(IRpcCallInfo client, byte[] arg) { if (_concurrency == ConcurrencyMode.Single) { //lock (this) //{ _operationPending.Reset(); try { return(Invoke(client, _endpoint._contractType, arg)); } finally { _operationPending.Set(); } //} } if (_concurrency == ConcurrencyMode.Multiple) { //BUG: need have collection of operations because second operation rewrites state of first _operationPending.Reset(); try { return(Invoke(client, _endpoint._contractType, arg)); } finally { _operationPending.Set(); } } throw new NotImplementedException( string.Format("ConcurrencyMode {0} is note implemented", _concurrency)); }; _host = RpcRequestReplyChannelFactory.CreateHost(_endpoint._binding, _endpoint._address, _endpoint._uuid); _host.OnExecute += onExecute; _host.StartListening(); } //_opened.Set(); } catch (Exception ex) { bool handled = ExceptionHandler.AlwaysHandle.HandleException(ex); if (!handled) { throw; } } }; //Tasks.Factory.StartNew(open); //_opened.WaitOne(); }
public EntityFrameworkSagaRepositoryConfigurator() { _isolationLevel = IsolationLevel.Serializable; _concurrencyMode = ConcurrencyMode.Pessimistic; _lockStatementProvider = new SqlServerLockStatementProvider(); }