Basic uses of the Async Tasks Framework.

Queuing agents for later execution.
AgentController controller = new AgentController();

for (int i = 0; i < 100; i++)
{
        // Queues the agent which is executed once Run() is called.
	controller.AddAgent(new ActionAgent<int>(i, Console.WriteLine));
}

// Execute all the queued agents.
controller.Run();


Executing the agent when it is added to the controller.
AgentController controller = new AgentController();

for (int i = 0; i < 100; i++)
{
        // Executes the agent.
	controller.Activate(new ActionAgent<int>(i, Console.WriteLine));
}


Extending agent to provide custom functionality.
public class EmailAgent : Agent<MailMessageModel>
{
	private SmtpClient client;

	public EmailAgent(MailMessageModel message) : base(message)
	{
	}

	public override void Execute()
	{
		client = new SmtpClient(Model.Host, Model.Port);
		client.Send(Model.Entity);
	}

	protected override void DisposeResources()
	{
		base.DisposeResources();

		if (client != null)
		{
			client.Dispose();
		}
	}
}

public class MailMessageModel : Model<MailMessage>
{
	public MailMessageModel(MailMessage entity) : base(entity)
	{
	}

	public string Host { get; set; }

	public int Port { get; set; }

	public void InitEntity()
	{
		// Initialize here or before it's passed in.
		Entity.To.Add("email@address.com");
		Entity.Body = "Here is my email";
		Entity.From = new MailAddress("support@domain.com");
	}
}

AgentController controller = new AgentController();

for (int i = 0; i < 100; i++)
{
	controller.Activate(new EmailAgent(new MailMessageModel(new MailMessage())
        {
            Host = "host",
            Port = 25
        }));
}

Last edited Dec 24, 2011 at 9:51 AM by sbaker, version 8

Comments

No comments yet.