我想排隊一系列任務並使用Azure服務結構異步運行它們。我目前正在使用具有輔助角色的CloudMessageQueue。我正在嘗試遷移到Service Fabric。從工人的角色,這是我的代碼:Azure服務結構消息隊列
private void ExecuteTask()
{
CloudQueueMessage message = null;
if (queue == null)
{
jmaLogProvider.WriteToLog(new ErrorMessage(MessageSeverity.Error, String.Format("Queue for WorkerRole2 is null. Exiting.")));
return;
}
try
{
message = queue.GetMessage();
if (message != null)
{
JMATask task = GetTask(message.AsString);
string msg = (message == null) ? string.Empty : message.AsString;
//jmaLogProvider.WriteToLog(new ErrorMessage(MessageSeverity.JMA, String.Format("Executing task {0}", msg)));
queue.DeleteMessage(message);
PerformTask(task);
}
}
catch (Exception ex)
{
string msg = (message == null) ? string.Empty : message.AsString;
jmaLogProvider.WriteToLog(new ErrorMessage(MessageSeverity.Error, String.Format("Message {0} Error removing message from queue {1}", msg, ex.ToString())));
}
}
我有一些問題:
- 如何運行的異步執行任務的方法?我想同時運行30-40個任務。
- 我有一個JMATask的列表。如何將列表添加到隊列中?
列表是否需要添加到隊列中?
namespace Stateful1 { public class JMATask { public string Name { get; set; } } /// <summary> /// An instance of this class is created for each service replica by the Service Fabric runtime. /// </summary> internal sealed class Stateful1 : StatefulService { public Stateful1(StatefulServiceContext context) : base(context) { } /// <summary> /// Optional override to create listeners (e.g., HTTP, Service Remoting, WCF, etc.) for this service replica to handle client or user requests. /// </summary> /// <remarks> /// For more information on service communication, see http://aka.ms/servicefabricservicecommunication /// </remarks> /// <returns>A collection of listeners.</returns> protected override IEnumerable<ServiceReplicaListener> CreateServiceReplicaListeners() { return new ServiceReplicaListener[0]; } /// <summary> /// This is the main entry point for your service replica. /// This method executes when this replica of your service becomes primary and has write status. /// </summary> /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param> protected override async Task RunAsync(CancellationToken cancellationToken) { // TODO: Replace the following sample code with your own logic // or remove this RunAsync override if it's not needed in your service. IReliableQueue<JMATask> tasks = await this.StateManager.GetOrAddAsync<IReliableQueue<JMATask>>("JMATasks"); //var myDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<string, long>>("myDictionary"); while (true) { cancellationToken.ThrowIfCancellationRequested(); using (var tx = this.StateManager.CreateTransaction()) { var result = await tasks.TryDequeueAsync(tx); //how do I execute this method async? PerformTask(result.Value); //Create list of JMA Tasks to queue up await tasks.EnqueueAsync(tx, new JMATask()); //var result = await myDictionary.TryGetValueAsync(tx, "Counter"); //ServiceEventSource.Current.ServiceMessage(this, "Current Counter Value: {0}", // result.HasValue ? result.Value.ToString() : "Value does not exist."); //await myDictionary.AddOrUpdateAsync(tx, "Counter", 0, (key, value) => ++value); // If an exception is thrown before calling CommitAsync, the transaction aborts, all changes are // discarded, and nothing is saved to the secondary replicas. await tx.CommitAsync(); } await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } } private async void PerformTask(JMATask task) { //execute task }
}
掙扎與類似的問題,這是有益的,謝謝。好奇你結束了什麼,以及它如何爲你工作。 – kenchilada
我使用了另一種技術:https://msdn.microsoft.com/en-us/library/dn568104.aspx –