C Sharp: Difference between revisions
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
==Usage== | |||
===Regular Expressions=== | |||
Regex<br> | |||
[https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.8 Reference] | |||
<syntaxhighlight lang="csharp"> | |||
using System; | |||
using System.Text.RegularExpressions; | |||
public class Test | |||
{ | |||
public static void Main () | |||
{ | |||
// Define a regular expression for repeated words. | |||
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b", | |||
RegexOptions.Compiled | RegexOptions.IgnoreCase); | |||
// Define a test string. | |||
string text = "The the quick brown fox fox jumps over the lazy dog dog."; | |||
// Find matches. | |||
MatchCollection matches = rx.Matches(text); | |||
// Report the number of matches found. | |||
Console.WriteLine("{0} matches found in:\n {1}", | |||
matches.Count, | |||
text); | |||
// Report on each match. | |||
foreach (Match match in matches) | |||
{ | |||
GroupCollection groups = match.Groups; | |||
Console.WriteLine("'{0}' repeated at positions {1} and {2}", | |||
groups["word"].Value, | |||
groups[0].Index, | |||
groups[1].Index); | |||
} | |||
} | |||
} | |||
</syntaxhighlight> | |||
==Multithreading== | ==Multithreading== |
Revision as of 16:39, 18 September 2019
Usage
Regular Expressions
Regex
Reference
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main ()
{
// Define a regular expression for repeated words.
Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a test string. <br />
string text = "The the quick brown fox fox jumps over the lazy dog dog.";
<br />
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count,
text);
// Report on each match.
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
Console.WriteLine("'{0}' repeated at positions {1} and {2}",<br />
groups["word"].Value,
groups[0].Index,
groups[1].Index);
}
}
}
Multithreading
Theadpool
C# has a convenient TheadPool class in the System.Threading namespace.
class TestClass {
static void Main(string[] args) {
int numberOfTasks = 10;
int tasksRemaining = 10;
// This is similar to a mutex.
ManualResetEvent finishedHandle = new ManualResetEvent(false);
for (int i = 0; i < numberOfTasks; i++) {
int j = i;
ThreadPool.QueueUserWorkItem(_ => {
try {
// Do something time consuming or resource intensive.
// Do not use i here. You can use j instead.
} catch (System.Exception e) {
// Print Stack Trace
} finally {
if (Interlocked.Decrement(ref tasksRemaining) == 0) {
finishedHandle.Set();
}
}
});
}
// Blocking wait.
finishedHandle.WaitOne();
}
}