Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- foreach (String item in ListOfStrings)
- {
- result.add(CalculateSmth(item));
- }
- Parallel.Foreach (ListOfStrings, (item) =>
- result.add(CalculateSmth(item));
- );
- using System.Collections.Generic;
- using System.Threading;
- namespace noocyte.Threading
- {
- class CalcState
- {
- public CalcState(ManualResetEvent reset, string input) {
- Reset = reset;
- Input = input;
- }
- public ManualResetEvent Reset { get; private set; }
- public string Input { get; set; }
- }
- class CalculateMT
- {
- List<string> result = new List<string>();
- List<ManualResetEvent> events = new List<ManualResetEvent>();
- private void Calc() {
- List<string> aList = new List<string>();
- aList.Add("test");
- foreach (var item in aList)
- {
- CalcState cs = new CalcState(new ManualResetEvent(false), item);
- events.Add(cs.Reset);
- ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), cs);
- }
- WaitHandle.WaitAll(events.ToArray());
- }
- private void Calculate(object s)
- {
- CalcState cs = s as CalcState;
- cs.Reset.Set();
- result.Add(cs.Input);
- }
- }
- }
- List<string> work = (some list with lots of strings)
- // Split the work in two
- List<string> odd = new List<string>();
- List<string> even = new List<string>();
- for (int i = 0; i < work.Count; i++)
- {
- if (i % 2 == 0)
- {
- even.Add(work[i]);
- }
- else
- {
- odd.Add(work[i]);
- }
- }
- // Set up to worker delegates
- List<Foo> oddResult = new List<Foo>();
- Action oddWork = delegate { foreach (string item in odd) oddResult.Add(CalculateSmth(item)); };
- List<Foo> evenResult = new List<Foo>();
- Action evenWork = delegate { foreach (string item in even) evenResult.Add(CalculateSmth(item)); };
- // Run two delegates asynchronously
- IAsyncResult evenHandle = evenWork.BeginInvoke(null, null);
- IAsyncResult oddHandle = oddWork.BeginInvoke(null, null);
- // Wait for both to finish
- evenWork.EndInvoke(evenHandle);
- oddWork.EndInvoke(oddHandle);
- // Merge the results from the two jobs
- List<Foo> allResults = new List<Foo>();
- allResults.AddRange(oddResult);
- allResults.AddRange(evenResult);
- return allResults;
Add Comment
Please, Sign In to add comment