Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created September 25, 2010 06:21
Show Gist options
  • Select an option

  • Save leandrosilva/596543 to your computer and use it in GitHub Desktop.

Select an option

Save leandrosilva/596543 to your computer and use it in GitHub Desktop.
Just a really dummy sample of parallel C# code (and also using continuations)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TaskParallelization
{
public class ParallelSender
{
private readonly IList<string> _contents;
private readonly ErrorLogger _errorLogger;
public ParallelSender(IList<string> contents)
{
_contents = contents;
_errorLogger = new ErrorLogger();
}
public void Send()
{
Console.WriteLine("Sending {0} contents...", _contents.Count);
var sendingTasks = _contents.Select(
content =>
{
var senderTask = new SenderTask(content, _errorLogger);
return Task.Factory.StartNew(() => senderTask.Do());
}
);
var dumpingLogTask = Task.Factory.ContinueWhenAll(
sendingTasks.ToArray(),
completedSendingTasks => _errorLogger.Dump()
);
dumpingLogTask.Wait();
Console.WriteLine("All contents were sent with sucess");
}
}
}
using System;
namespace TaskParallelization
{
class SenderTask
{
private readonly string _input;
private readonly ErrorLogger _errorLogger;
public SenderTask(string input, ErrorLogger errorLogger)
{
_input = input;
_errorLogger = errorLogger;
}
public bool Do()
{
try
{
Console.WriteLine("- Sending {0}", _input);
return true;
}
catch (Exception e)
{
_errorLogger.Log(String.Format("- An error sending {0}: {1}", _input, e.Message));
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment