/// <summary> /// Constructs the step, using the specified <see cref="ITimeoutManager"/> to defer relevant messages /// and the specified <see cref="ITransport"/> to deliver messages when they're due. /// </summary> public HandleDeferredMessagesStep(ITimeoutManager timeoutManager, ITransport transport, Options options, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { if (timeoutManager == null) { throw new ArgumentNullException(nameof(timeoutManager)); } if (transport == null) { throw new ArgumentNullException(nameof(transport)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _timeoutManager = timeoutManager; _transport = transport; _options = options; _log = rebusLoggerFactory.GetCurrentClassLogger(); var dueTimeoutsPollIntervalSeconds = (int)options.DueTimeoutsPollInterval.TotalSeconds; var intervalToUse = dueTimeoutsPollIntervalSeconds >= 1 ? dueTimeoutsPollIntervalSeconds : 1; _dueMessagesSenderBackgroundTask = asyncTaskFactory.Create(DueMessagesSenderTaskName, TimerElapsed, intervalSeconds: intervalToUse); }
public ReplyHandlerStep(ConcurrentDictionary <string, TimedMessage> messages, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, TimeSpan replyMaxAge) { _messages = messages ?? throw new ArgumentNullException(nameof(messages)); _log = rebusLoggerFactory?.GetLogger <ReplyHandlerStep>() ?? throw new ArgumentNullException(nameof(rebusLoggerFactory)); _cleanupTask = asyncTaskFactory?.Create("CleanupAbandonedRepliesTask", CleanupAbandonedReplies) ?? throw new ArgumentNullException(nameof(asyncTaskFactory)); _replyMaxAge = replyMaxAge; }
/// <summary> /// Constructor /// </summary> /// <param name="connectionProvider">A <see cref="IDbConnection"/> to obtain a database connection</param> /// <param name="lockTableName">Name of the queue this transport is servicing</param> /// <param name="rebusLoggerFactory">A <seealso cref="IRebusLoggerFactory"/> for building loggers</param> /// <param name="asyncTaskFactory">A <seealso cref="IAsyncTaskFactory"/> for creating periodic tasks</param> /// <param name="rebusTime">A <seealso cref="IRebusTime"/> to provide the current time</param> /// <param name="options">Additional options</param> public MySqlExclusiveAccessLock( IDbConnectionProvider connectionProvider, string lockTableName, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, IRebusTime rebusTime, MySqlExclusiveAccessLockOptions options) { if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _rebusTime = rebusTime ?? throw new ArgumentNullException(nameof(rebusTime)); _connectionProvider = connectionProvider ?? throw new ArgumentNullException(nameof(connectionProvider)); _lockTableName = lockTableName != null?TableName.Parse(lockTableName) : null; _log = rebusLoggerFactory.GetLogger <MySqlExclusiveAccessLock>(); _lockExpirationTimeout = options.LockExpirationTimeout ?? DefaultLockExpirationTimeout; var cleanupInterval = options.ExpiredLocksCleanupInterval ?? DefaultExpiredLocksCleanupInterval; var intervalSeconds = (int)cleanupInterval.TotalSeconds; _expiredLocksCleanupTask = asyncTaskFactory.Create("ExpiredLocksCleanup", PerformExpiredLocksCleanupCycle, intervalSeconds: intervalSeconds); _autoDeleteTable = options.AutoDeleteTable; }
public ReplyHandlerStep(ConcurrentDictionary<string, TimedMessage> messages, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, TimeSpan replyMaxAge) { _messages = messages; _replyMaxAge = replyMaxAge; _log = rebusLoggerFactory.GetCurrentClassLogger(); _cleanupTask = asyncTaskFactory.Create("CleanupAbandonedRepliesTask", CleanupAbandonedReplies); }
/// <summary> /// /// </summary> /// <param name="connectionHelper"></param> /// <param name="tableName"></param> /// <param name="inputQueueName"></param> /// <param name="rebusLoggerFactory"></param> /// <param name="asyncTaskFactory"></param> public PostgreSqlTransport(PostgresConnectionHelper connectionHelper, string tableName, string inputQueueName, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { if (connectionHelper == null) { throw new ArgumentNullException(nameof(connectionHelper)); } if (tableName == null) { throw new ArgumentNullException(nameof(tableName)); } if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _log = rebusLoggerFactory.GetLogger <PostgreSqlTransport>(); _connectionHelper = connectionHelper; _tableName = tableName; _inputQueueName = inputQueueName; _expiredMessagesCleanupTask = asyncTaskFactory.Create("ExpiredMessagesCleanup", PerformExpiredMessagesCleanupCycle, intervalSeconds: 60); ExpiredMessagesCleanupInterval = DefaultExpiredMessagesCleanupInterval; }
protected override void Beat() { IInternalMessage message = SystemMessageQueue.Instance.Poll(); if (message != null) { switch (message.GetMessageId()) { case AsyncTaskMessage.ASYNC_MESSAGE_ID: { AsyncTaskMessage asyncTaskMessage = message as AsyncTaskMessage; AsyncState state = asyncTaskMessage.State; IAsyncTask asyncTask = asyncTaskMessage.AsyncTask; if (state == AsyncState.DoAsync) { throw new ApplicationException(string.Format("asyncTask:{0} [DoAsyncTask] infinite loop.", asyncTask.GetType().FullName)); } AsyncManager.Instance.ExecuteAsyncTask(state, asyncTask); break; } default: { break; } } } }
public ReplyHandlerStep(ConcurrentDictionary <string, TimedMessage> messages, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, TimeSpan replyMaxAge) { _messages = messages; _replyMaxAge = replyMaxAge; _log = rebusLoggerFactory.GetCurrentClassLogger(); _cleanupTask = asyncTaskFactory.Create("CleanupAbandonedRepliesTask", CleanupAbandonedReplies); }
/// <summary> /// 添加任务列表 /// </summary> /// <param name="tasks"></param> /// <param name="weight"></param> /// <returns>开始任务数量</returns> public int AddTasks(IList <IAsyncTask> tasks, float weight = 1) { lock (mLock) { if (IsDone || weight <= 0 || tasks == null || tasks.Count == 0) { return(0); } float eweight = weight / tasks.Count; int len = 0; for (int i = 0; i < tasks.Count; i++) { IAsyncTask task = tasks[i]; if (task != null && !task.IsDone) { Task t = new Task(); t.task = task; t.weight = eweight; mTotalWeight += eweight; mTasks.Add(t); if (mStarted) { task.OnStart(); } len++; } } return(len); } }
protected override IEnumerator DoTransition() { Window current = this.Window; if (this.manager.IndexOf(current) == 0) { if (current.Activated) { IAsyncTask passivate = current.Passivate(this.AnimationDisabled).Start(); yield return(passivate.WaitForDone()); } if (current.Visibility) { IAsyncTask hide = current.DoHide(this.AnimationDisabled).Start(); yield return(hide.WaitForDone()); } } else { if (current.Visibility) { IAsyncTask hide = current.DoHide(this.AnimationDisabled).Start(); yield return(hide.WaitForDone()); } } if (dismiss) { current.DoDismiss(); } }
/// <summary> /// 异步加载场景 /// </summary> /// <param name="scenePath"></param> /// <param name="isAdditive"></param> /// <returns></returns> public IEnumerator LoadSceneAsync(string scenePath, bool isAdditive) { LoadSceneMode mode = isAdditive ? LoadSceneMode.Additive : LoadSceneMode.Single; string assetBundleName = mAssetManifest[scenePath]; string[] split = scenePath.Replace('\\', '/').Split('/'); string sceneName = split[split.Length - 1].Replace(".unity", ""); bool needLoadAssetBundle = !UnityUtility.IsSceneInBuildSetting(sceneName); if (needLoadAssetBundle) { IAsyncTask bundleTask = mAssetBundleHelper.LoadAssetBundleAsync(assetBundleName, null); while (bundleTask.Status != TaskStatus.Completed) { yield return(null); } } AsyncOperation operation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName, mode); while (!operation.isDone) { yield return(null); } if (needLoadAssetBundle) { mAssetBundleHelper.Unload(assetBundleName); } }
/// <summary> /// Constructs the in-mem error tracker with the configured number of delivery attempts as the MAX /// </summary> public InMemErrorTracker(int maxDeliveryAttempts, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { if (rebusLoggerFactory == null) throw new ArgumentNullException(nameof(rebusLoggerFactory)); if (asyncTaskFactory == null) throw new ArgumentNullException(nameof(asyncTaskFactory)); _maxDeliveryAttempts = maxDeliveryAttempts; _log = rebusLoggerFactory.GetCurrentClassLogger(); _cleanupOldTrackedErrorsTask = asyncTaskFactory.Create(BackgroundTaskName, CleanupOldTrackedErrors, intervalSeconds: 60); }
/// <summary> /// Add a low priority event to the event queue /// </summary> /// <param name="evnt">event</param> public void Enqueue(IAsyncTask evnt) { lock (this) { _eventsHi.Enqueue(evnt); Monitor.Pulse(this); } }
/// <summary> /// Constructs the step, using the specified <see cref="ITimeoutManager"/> to defer relevant messages /// and the specified <see cref="ITransport"/> to deliver messages when they're due. /// </summary> public HandleDeferredMessagesStep(ITimeoutManager timeoutManager, ITransport transport, Options options, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { _timeoutManager = timeoutManager; _transport = transport; _options = options; _log = rebusLoggerFactory.GetCurrentClassLogger(); _dueMessagesSenderBackgroundTask = asyncTaskFactory.Create(DueMessagesSenderTaskName, TimerElapsed, intervalSeconds: 1); }
protected void startInitialization() { if (_asyncTaskCreator != null) { _asyncTask = _asyncTaskCreator.CreateAsyncTask <TModel, int, object>(GetInitializer ()); _asyncTask.Execute(_model); } }
/// <summary> /// Constructs the step, using the specified <see cref="ITimeoutManager"/> to defer relevant messages /// and the specified <see cref="ITransport"/> to deliver messages when they're due. /// </summary> public HandleDeferredMessagesStep(ITimeoutManager timeoutManager, ITransport transport, Options options, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { _timeoutManager = timeoutManager; _transport = transport; _options = options; _log = rebusLoggerFactory.GetCurrentClassLogger(); _dueMessagesSenderBackgroundTask = asyncTaskFactory.Create(DueMessagesSenderTaskName, TimerElapsed, intervalSeconds: 1); }
public IAsyncTask LoadAssetAsync <T>(string assetPath, Action <bool, T> callback) where T : UnityEngine.Object { string assetBundleName = mAssetManifest[assetPath]; LoadAssetTask <T> assetTask = new LoadAssetTask <T>(assetPath, assetBundleName, mAssetBundleHelper, callback); IAsyncTask bundleTask = mAssetBundleHelper.LoadAssetBundleAsync(assetBundleName, assetTask.OnAssetBundleLoadCompleted); assetTask.bundleTask = bundleTask; return(assetTask); }
public MainCircuitBreaker(IList <ICircuitBreaker> circuitBreakers, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, Lazy <IBus> bus, CircuitBreakerEvents circuitBreakerEvents, Options options) { _log = rebusLoggerFactory?.GetLogger <MainCircuitBreaker>() ?? throw new ArgumentNullException(nameof(rebusLoggerFactory)); _circuitBreakers = circuitBreakers ?? new List <ICircuitBreaker>(); _bus = bus ?? throw new ArgumentNullException(nameof(bus)); _circuitBreakerEvents = circuitBreakerEvents; _options = options; _resetCircuitBreakerTask = asyncTaskFactory.Create(BackgroundTaskName, Reset, prettyInsignificant: true, intervalSeconds: 2); }
/// <summary> /// 线程池调用 /// </summary> /// <param name="o"></param> private void AsyncExecute(object o) { IAsyncTask asyncTask = o as IAsyncTask; AsyncState newState = asyncTask.DoAsyncTask(); AsyncTaskMessage message = new AsyncTaskMessage(); message.State = newState; message.AsyncTask = asyncTask; SystemMessageQueue.Instance.Offer(message); }
/// <summary> /// Constructs a MySql transport. /// </summary> /// <param name="connectionHelper"></param> /// <param name="tableName">The name of the table used as the transport.</param> /// <param name="inputQueueName">The name of the queue on which messages are received.</param> /// <param name="rebusLoggerFactory"></param> /// <param name="asyncTaskFactory"></param> public MySqlTransport(MySqlConnectionHelper connectionHelper, string tableName, string inputQueueName, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { _connectionHelper = connectionHelper; _tableName = tableName; _inputQueueName = inputQueueName; _asyncTaskFactory = asyncTaskFactory; ExpiredMessagesCleanupInterval = DefaultExpiredMessagesCleanupInterval; _expiredMessagesCleanupTask = asyncTaskFactory.Create("ExpiredMessagesCleanup", PerformExpiredMessagesCleanupCycle, intervalSeconds: 60); _log = rebusLoggerFactory.GetLogger <MySqlTransport>(); }
/// <summary> /// Constructs the transport with the given <see cref="IDbConnectionProvider"/>, using the specified <paramref name="tableName"/> to send/receive messages, /// querying for messages with recipient = <paramref name="inputQueueName"/> /// </summary> public SqlServerTransport(IDbConnectionProvider connectionProvider, string tableName, string inputQueueName, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { _connectionProvider = connectionProvider; _tableName = tableName; _inputQueueName = inputQueueName; _log = rebusLoggerFactory.GetCurrentClassLogger(); ExpiredMessagesCleanupInterval = DefaultExpiredMessagesCleanupInterval; _expiredMessagesCleanupTask = asyncTaskFactory.Create("ExpiredMessagesCleanup", PerformExpiredMessagesCleanupCycle, intervalSeconds: 60); }
public static string Register(IAsyncTask task, string name, string detailInfo = "", bool allowDuplicate = true) { if (EngineCts.IsCancellationRequested || string.IsNullOrWhiteSpace(task.ReferenceKey) || string.IsNullOrWhiteSpace(name) || !allowDuplicate && Instance.TaskList.Any(registredTask => registredTask.Value.Task.ReferenceKey.Equals(task.ReferenceKey))) { return(string.Empty); } return(Instance.RegisterImpl(task, name, detailInfo)); }
public TaskRecord(IAsyncTask task, string name = "", string detail = "") { if (null == task) { throw new NullReferenceException(); } Task = task; Status = Status.Pendding; RunningTask = null; Name = name; DetailInfo = detail; }
/// <summary> /// Constructs the in-mem error tracker with the configured number of delivery attempts as the MAX /// </summary> public InMemErrorTracker(int maxDeliveryAttempts, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _maxDeliveryAttempts = maxDeliveryAttempts; _log = rebusLoggerFactory.GetLogger <InMemErrorTracker>(); _cleanupOldTrackedErrorsTask = asyncTaskFactory.Create(BackgroundTaskName, CleanupOldTrackedErrors, intervalSeconds: 60); }
public AutoScaler(ITransport transport, IRebusLoggerFactory rebusLoggerFactory, int maximumNumberOfWorkers, IAsyncTaskFactory asyncTaskFactory, Func <IBus> busFactory, int adjustmentIntervalSeconds) { if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _logger = rebusLoggerFactory.GetLogger <AutoScaler>(); _transport = transport ?? throw new ArgumentNullException(nameof(transport)); _maximumNumberOfWorkers = maximumNumberOfWorkers; _busFactory = busFactory ?? throw new ArgumentNullException(nameof(busFactory)); _task = asyncTaskFactory.Create("AutoScale", Tick, intervalSeconds: adjustmentIntervalSeconds); }
protected override IEnumerator DoTransition() { Window current = this.Window; Window previous = this.manager.Current as Window; if (previous != null) { //Passivate the previous window if (previous.Activated) { IAsyncTask passivate = previous.Passivate(this.AnimationDisabled).Start(); yield return(passivate.WaitForDone()); } ActionType actionType = this.Overlay(previous, current); switch (actionType) { case ActionType.Hide: previous.DoHide(this.AnimationDisabled).Start(); break; case ActionType.Dismiss: previous.DoHide(this.AnimationDisabled).OnFinish(() => { previous.DoDismiss(); }).Start(); break; default: break; } } if (!current.Visibility) { IAsyncTask show = current.DoShow(this.AnimationDisabled).Start(); yield return(show.WaitForDone()); } if (this.manager.Activated && current.Equals(this.manager.Current)) { IAsyncTask activate = current.Activate(this.AnimationDisabled).Start(); yield return(activate.WaitForDone()); } }
/// <summary> /// Constructs the transport, connecting to the service bus pointed to by the connection string. /// </summary> public AzureServiceBusTransport(string connectionString, string queueName, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, INameFormatter nameFormatter, CancellationToken cancellationToken = default(CancellationToken), ITokenProvider tokenProvider = null) { if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _nameFormatter = nameFormatter; if (queueName != null) { // this never happens if (queueName.StartsWith(MagicSubscriptionPrefix)) { throw new ArgumentException($"Sorry, but the queue name '{queueName}' cannot be used because it conflicts with Rebus' internally used 'magic subscription prefix': '{MagicSubscriptionPrefix}'. "); } Address = _nameFormatter.FormatQueueName(queueName); _subscriptionName = _nameFormatter.FormatSubscriptionName(queueName); } _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _cancellationToken = cancellationToken; _log = rebusLoggerFactory.GetLogger <AzureServiceBusTransport>(); if (tokenProvider != null) { var connectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString); _managementClient = new ManagementClient(connectionStringBuilder, tokenProvider); _endpoint = connectionStringBuilder.Endpoint; _transportType = connectionStringBuilder.TransportType; } else { _managementClient = new ManagementClient(connectionString); } _tokenProvider = tokenProvider; _messageLockRenewalTask = asyncTaskFactory.Create("Peek Lock Renewal", RenewPeekLocks, prettyInsignificant: true, intervalSeconds: 10); }
/// <summary> /// Constructor /// </summary> /// <param name="connectionProvider">A <see cref="IDbConnection"/> to obtain a database connection</param> /// <param name="inputQueueName">Name of the queue this transport is servicing</param> /// <param name="rebusLoggerFactory">A <seealso cref="IRebusLoggerFactory"/> for building loggers</param> /// <param name="asyncTaskFactory">A <seealso cref="IAsyncTaskFactory"/> for creating periodic tasks</param> /// <param name="rebusTime">A <seealso cref="IRebusTime"/> to provide the current time</param> /// <param name="options">Additional options</param> public MySqlTransport( IDbConnectionProvider connectionProvider, string inputQueueName, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory, IRebusTime rebusTime, MySqlTransportOptions options) { if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _rebusTime = rebusTime ?? throw new ArgumentNullException(nameof(rebusTime)); _connectionProvider = connectionProvider ?? throw new ArgumentNullException(nameof(connectionProvider)); _receiveTableName = inputQueueName != null?TableName.Parse(inputQueueName) : null; _log = rebusLoggerFactory.GetLogger <MySqlTransport>(); var cleanupInterval = options.ExpiredMessagesCleanupInterval ?? DefaultExpiredMessagesCleanupInterval; var intervalSeconds = (int)cleanupInterval.TotalSeconds; _expiredMessagesCleanupTask = asyncTaskFactory.Create("ExpiredMessagesCleanup", PerformExpiredMessagesCleanupCycle, intervalSeconds: intervalSeconds); _autoDeleteQueue = options.AutoDeleteQueue; _leasedByFactory = options.LeasedByFactory ?? (() => Environment.MachineName); _leaseInterval = options.LeaseInterval ?? DefaultLeaseTime; _leaseTolerance = options.LeaseInterval ?? DefaultLeaseTolerance; _ensureTablesAreCreated = options.EnsureTablesAreCreated; var automaticLeaseRenewalInterval = options.LeaseAutoRenewInterval; if (!automaticLeaseRenewalInterval.HasValue) { _automaticLeaseRenewal = false; } else { _automaticLeaseRenewal = true; _automaticLeaseRenewalInterval = automaticLeaseRenewalInterval.Value; } }
/// <summary> /// Constructs the step, using the specified <see cref="ITimeoutManager"/> to defer relevant messages /// and the specified <see cref="ITransport"/> to deliver messages when they're due. /// </summary> public HandleDeferredMessagesStep(ITimeoutManager timeoutManager, ITransport transport, Options options, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { if (timeoutManager == null) throw new ArgumentNullException(nameof(timeoutManager)); if (transport == null) throw new ArgumentNullException(nameof(transport)); if (options == null) throw new ArgumentNullException(nameof(options)); if (rebusLoggerFactory == null) throw new ArgumentNullException(nameof(rebusLoggerFactory)); if (asyncTaskFactory == null) throw new ArgumentNullException(nameof(asyncTaskFactory)); _timeoutManager = timeoutManager; _transport = transport; _options = options; _log = rebusLoggerFactory.GetCurrentClassLogger(); var dueTimeoutsPollIntervalSeconds = (int)options.DueTimeoutsPollInterval.TotalSeconds; var intervalToUse = dueTimeoutsPollIntervalSeconds >= 1 ? dueTimeoutsPollIntervalSeconds : 1; _dueMessagesSenderBackgroundTask = asyncTaskFactory.Create(DueMessagesSenderTaskName, TimerElapsed, intervalSeconds: intervalToUse); }
/// <summary> /// Constructs the step, using the specified <see cref="ITimeoutManager"/> to defer relevant messages /// and the specified <see cref="ITransport"/> to deliver messages when they're due. /// </summary> public HandleDeferredMessagesStep(ITimeoutManager timeoutManager, ITransport transport, Options options, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { if (rebusLoggerFactory == null) { throw new ArgumentNullException(nameof(rebusLoggerFactory)); } if (asyncTaskFactory == null) { throw new ArgumentNullException(nameof(asyncTaskFactory)); } _timeoutManager = timeoutManager ?? throw new ArgumentNullException(nameof(timeoutManager)); _transport = transport ?? throw new ArgumentNullException(nameof(transport)); _options = options ?? throw new ArgumentNullException(nameof(options)); _log = rebusLoggerFactory.GetLogger <HandleDeferredMessagesStep>(); _dueMessagesSenderBackgroundTask = asyncTaskFactory.Create(DueMessagesSenderTaskName, TimerElapsed, interval: options.DueTimeoutsPollInterval); }
/// <summary> /// Método acionado pelo robo do processador. /// </summary> protected void Run() { while (_worker != null) { IAsyncTask task = null; try { lock (this) { if ((_eventsHi.Count < 1) && (_eventsLow.Count < 1)) { Monitor.Wait(this); } if (_eventsHi.Count > 0) { task = _eventsHi.Dequeue(); } else if (_eventsLow.Count > 0) { task = _eventsLow.Dequeue(); } } if (task != null) { task.Process(); } continue; } catch (ThreadAbortException) { break; } catch (NullReferenceException) { continue; } catch (Exception) { continue; } } }
/// <summary> /// 添加任务 /// </summary> /// <param name="task"></param> /// <param name="weight"></param> /// <returns></returns> public bool AddTask(IAsyncTask task, float weight = 1) { lock (mLock) { if (IsDone || task == null || task.IsDone || weight <= 0) { return(false); } Task t = new Task(); t.task = task; t.weight = weight; mTotalWeight += weight; mTasks.Add(t); if (mStarted) { task.Start(); } return(true); } }
/// <summary> /// 指定异步任务状态,并从指定的状态开始执行,必须由主线程来调用 /// </summary> /// <param name="state">指定异步任务的状态</param> /// <param name="asyncTask">异步任务对象</param> public void ExecuteAsyncTask(AsyncState state, IAsyncTask asyncTask) { switch (state) { case AsyncState.BeforeAsync: { //异步开始前执行,由主线程调用 AsyncState newState = asyncTask.BeforeAsyncTask(); if (newState == AsyncState.BeforeAsync) { throw new ApplicationException(string.Format("asyncTask:{0} [BeforeAsyncTask] infinite loop.", asyncTask.GetType().FullName)); } this.ExecuteAsyncTask(newState, asyncTask); break; } case AsyncState.DoAsync: { //需要异步执行,委托线程池来执行该任务 ThreadPool.QueueUserWorkItem(new WaitCallback(AsyncExecute), asyncTask); break; } case AsyncState.AfterAsync: { AsyncState newState = asyncTask.AfterAsyncTask(); if (newState == AsyncState.AfterAsync) { throw new ApplicationException(string.Format("asyncTask:{0} [AfterAsyncTask] infinite loop.", asyncTask.GetType().FullName)); } this.ExecuteAsyncTask(newState, asyncTask); break; } default: { break; } } }
/// <summary> /// Add a low priority event to the event queue /// </summary> /// <param name="evnt">event</param> public void EnqueueLowPriority(IAsyncTask evnt) { lock (this) { _eventsLow.Enqueue(evnt); Monitor.Pulse(this); } }
private void btnExport_Click(object sender, EventArgs e) { rbMessage.Clear(); exportTask = new DataExporter(); exportTask.RunAsync(@"c:\\TestDataFile.txt"); exportTask.ProgressChanged += new ProgressChangedEventHandler(delegate(object o, ProgressChangedEventArgs args) { if (args != null && args.UserState != null) { this.rbMessage.AppendText(args.UserState.ToString()); } }); exportTask.Completed += new AsyncCompletedEventHandler(delegate(object o, AsyncCompletedEventArgs args) { this.rbMessage.AppendText("Export Successfuly."); }); }
/// <summary> /// 以BeforeAsyncTask状态开始执行一个异步任务,必须由主线程来调用 /// </summary> /// <param name="asyncTask">异步任务对象</param> public void ExecuteAsyncTask(IAsyncTask asyncTask) { this.ExecuteAsyncTask(AsyncState.BeforeAsync, asyncTask); }
/// <summary> /// Constructs the in-mem error tracker with the configured number of delivery attempts as the MAX /// </summary> public InMemErrorTracker(int maxDeliveryAttempts, IRebusLoggerFactory rebusLoggerFactory, IAsyncTaskFactory asyncTaskFactory) { _maxDeliveryAttempts = maxDeliveryAttempts; _log = rebusLoggerFactory.GetCurrentClassLogger(); _cleanupOldTrackedErrorsTask = asyncTaskFactory.Create(BackgroundTaskName, CleanupOldTrackedErrors, intervalSeconds: 60); }