Created
September 25, 2010 06:21
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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