using System


using System;//12
using System.Collections.Generic;
//—оздать на ¤зыке C# статический метод Where статического класса StringListEnumerator, который:
//- имеет вид:
//public static IEnumerable<string> Where(this IEnumerable<string> source, Func<string, bool> predicate);
//- реализует шаблон Enumerator и возвращает только те элементы переданного виртуального списка source, дл¤ которых делегат predicate возвращает значение true.
//–еализовать простейший пример использовани¤ метода StringListEnumerator.Where.
namespace ћусор{
static class StringListEnumerator {
public static IEnumerable<string> Where(this IEnumerable<string> source, Func<string, bool> predicate)
{
foreach (var element in source)
{
if (predicate(element))
{
yield return element;
}
}
}
}
static class Program
{
static void Main(string[] args)
{
var testCollection = new string[] { "a", "aa", "aaa", "aaaa" };
var filteredCollection = testCollection.Where(s => s.Length % 2 == 0);
foreach (var element in filteredCollection)
{
Console.WriteLine(element);
}
Console.ReadKey();
}
}
} using System;//2
using System.Collections.Concurrent;
using System.Threading;
namespace Мусор{
public delegate void TaskDelegate();
public class TaskQueue {
private readonly BlockingCollection<TaskDelegate> _blockingQueue = new BlockingCollection<TaskDelegate>(new ConcurrentQueue<TaskDelegate>());
public TaskQueue(int threadCount)
{
for (var i = 0; i < threadCount; i++)
{
var thread = new Thread(DoThreadWork) {IsBackground = true};
thread.Start();
} }
public void EnqueueTask(TaskDelegate task)
{ _blockingQueue.Add(task); }
private void DoThreadWork()
{
while (true)
{
var task = _blockingQueue.Take();
try
{ task(); }
catch (ThreadAbortException)
{ Thread.ResetAbort(); }
catch (Exception ex)
{ Console.WriteLine(ex.ToString()); } } } }
static class Program
{
private static void TestTask()
{
Console.WriteLine("TestTask in thread #" + Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(3000);
}
static void Main(string[] args)
{
var taskQueue = new TaskQueue(3);
for (var i = 0; i < 10; i++)
{
taskQueue.EnqueueTask(TestTask);
}
Console.ReadLine();
}
}
} using System;//3
using System.Runtime.InteropServices;
namespace ћусор{
class OsHandle : IDisposable
{
[DllImport("Kernel32.dll")]
private static extern bool CloseHandle(IntPtr handle);
private bool _disposed = false;
public IntPtr Handle { get; set; }
public OsHandle()
{
Handle = IntPtr.Zero;
}
~OsHandle()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Close()
{
Dispose();
}
protected virtual void Dispose(bool disposing)
{
lock (this)
{
if (!_disposed && Handle != IntPtr.Zero)
{
CloseHandle(Handle);
Handle = IntPtr.Zero;
}
_disposed = true;
}
}
}
static class Program
{
static void Main(string[] args)
{
}
}
}
using System;//6
using System.Linq;
using System.Reflection;
namespace B
{
public class PublicClass1 { }
public class PublicClass2 { }
public enum PublicEnum { };
internal class InternalClass { }
}
namespace A
{
static class Program
{
static void ListTypesInAssembly(Assembly assembly)
{
var types = assembly.GetTypes().Where(t => t.IsPublic).OrderBy(t => t.Namespace + t.Name);
foreach (var type in types)
{
Console.WriteLine(type.FullName);
} }
static void Main(string[] args)
{
var assemblyPath = Assembly.GetExecutingAssembly().Location;
var assembly = Assembly.LoadFrom(assemblyPath);
ListTypesInAssembly(assembly);
Console.ReadKey();
}
}
public class PublicClass1 {}
public class PublicClass2 {}
public enum PublicEnum {};
internal class InternalClass {}
} using System;//5
using System.Threading;
namespace ћусор{
class Mutex {
private int _holderId = -1;
public void Lock()
{
var id = Thread.CurrentThread.ManagedThreadId;
while (Interlocked.CompareExchange(ref _holderId, id, -1) != -1)
{
Thread.Sleep(10);
} }
public void Unlock()
{
var id = Thread.CurrentThread.ManagedThreadId;
Interlocked.CompareExchange(ref _holderId, -1, id);
} }
static class Program
{
static void Main(string[] args)
{
var mutex = new Mutex();
for (var i = 0; i < 10; i++)
{
new Thread(() =>
{ mutex.Lock();
Console.WriteLine("Thread #" + Thread.CurrentThread.ManagedThreadId + " locked mutex.");
Thread.Sleep(400);
Console.WriteLine("Thread #" + Thread.CurrentThread.ManagedThreadId + " unlocked mutex.");
mutex.Unlock();
}).Start(); }
Console.ReadLine(); } }} using System;//4
using System.IO;
using System.Threading;
namespace ћусор{
public class LogFile : IDisposable
{
private readonly StreamWriter _writer;
public LogFile(string filePath)
{
_writer = new StreamWriter(filePath);
}
public void Dispose()
{
_writer.Close();
}
public void Write(string str)
{
_writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF ") + Thread.CurrentThread.ManagedThreadId + " " + str);
}
}
static class Program
{
static void Main(string[] args)
{
using (var logFile = new LogFile(@"C:\log.txt"))
{
for (var i = 0; i < 10; i++)
{
logFile.Write(Guid.NewGuid().ToString());
}
}
}
}
}
using System;//1
using System.Collections.Concurrent;
using System.IO;
using System.Threading.Tasks;
namespace Мусор{
class FileStreamWorker : IDisposable
{
private readonly BlockingCollection<Tuple<byte[], int>> _blockingQueue = new BlockingCollection<Tuple<byte[], int>>(new ConcurrentQueue<Tuple<byte[], int>>());
private const int BlockSize = 1024 * 1024;
private readonly FileStream _readStream;
private readonly FileStream _writeStream;
public FileStreamWorker(string readPath, string writePath)
{
_readStream = new FileStream(readPath, FileMode.Open, FileAccess.Read, FileShare.Read, BlockSize * 2, true);
_writeStream = new FileStream(writePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, BlockSize * 2, true);
}
public void CopyFileAsync()
{
Parallel.Invoke(ReadFile, WriteFile);
}
private void ReadFile()
{
var bytesRead = 0;
do
{
var buffer = new byte[BlockSize];
var result = _readStream.BeginRead(buffer, 0, buffer.Length, null, null);
Console.Write(".");
bytesRead = _readStream.EndRead(result);
_blockingQueue.Add(new Tuple<byte[], int>(buffer, bytesRead));
} while (bytesRead > 0);
}
private void WriteFile()
{
var bytesWrite = 0;
do
{
var block = _blockingQueue.Take();
var buffer = block.Item1;
bytesWrite = block.Item2;
var result = _writeStream.BeginWrite(buffer, 0, bytesWrite, null, null);
Console.Write(".");
_writeStream.EndWrite(result);
} while (bytesWrite == BlockSize);
}
public void Dispose()
{
_readStream.Close();
_writeStream.Close();
}
}
static class Program
{
static void Main(string[] args)
{
const string inFile = @"C:\\in";
const string outFile = @"C:\\out";
using (var stream = new FileStreamWorker(inFile, outFile))
{
stream.CopyFileAsync();
}
Console.ReadKey();
}
}
} using System;//7
using System.Threading;
namespace ћусор{
static class Program
{
static void Main(string[] args)
{
var oc1 = new ObjectCounter();
var oc2 = new ObjectCounter();
Console.WriteLine("2xObjectCounter, 0xObjectCounterExtended, count = " + ObjectCounter.Count);
var oce1 = new ObjectCounterExtended();
var oce2 = new ObjectCounterExtended();
Console.WriteLine("2xObjectCounter, 2xObjectCounterExtended, count = " + ObjectCounter.Count);
oc1 = null;
oce1 = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("1xObjectCounter, 1xObjectCounterExtended, count = " + ObjectCounter.Count);
oc2 = null;
oce2 = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("0xObjectCounter, 0xObjectCounterExtended, count = " + ObjectCounter.Count);
Console.ReadKey();
}
}
[DisableCounting]
public class ObjectCounter {
private static int _count = 0;
public static int Count
{
get { return _count; }
}
public ObjectCounter()
{
if (!this.GetType().IsDefined(typeof (DisableCountingAttribute), false))
{
Interlocked.Increment(ref _count);
}
}
~ObjectCounter()
{
if (!this.GetType().IsDefined(typeof(DisableCountingAttribute), false))
{
Interlocked.Decrement(ref _count);
}
}
}
public class ObjectCounterExtended : ObjectCounter {}
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public sealed class DisableCountingAttribute : Attribute {}
} using System;//16
using System.Collections;
using System.Collections.Generic;namespace ћусор{
class DynamicList<T> : IEnumerable<T>
{
private T[] _container;
private int _nextPosition = 0;
public void Add(T value)
{
EnsureCapacity();
_container[_nextPosition] = value;
_nextPosition++;
}
public void Remove(T value)
{
RemoveAt(Array.IndexOf(_container, value));
}
public void RemoveAt(int index)
{
var newContainer = new T[_container.Length - 1];
Array.Copy(_container, newContainer, index);
Array.Copy(_container, index + 1, newContainer, index, _container.Length - index - 1);
_container = newContainer;
_nextPosition--;
}
public void Clear()
{
_container = null;
_nextPosition = 0;
}
public int Count
{
get { return _nextPosition; }
}
public T this[int index]
{
get { return _container[index]; }
set { _container[index] = value; }
}
public IEnumerator<T> GetEnumerator()
{
for (var i = 0; i < _nextPosition; i++)
{
yield return _container[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void EnsureCapacity()
{
if (_container == null)
{
_container = new T[16];
}
if (_nextPosition == _container.Length)
{
var newContainer = new T[_container.Length + 16];
Array.Copy(_container, newContainer, _container.Length);
_container = newContainer;
}
}
}
static class Program
{
static void Main(string[] args)
{
var dynamicList = new DynamicList<int>();
for (var i = 0; i <= 128; i++)
{
dynamicList.Add(i);
}
foreach (var element in dynamicList)
{
Console.Write(element + " ");
}
Console.WriteLine();
for (var i = 32; i <= 64; i++)
{
dynamicList.Remove(i);
}
foreach (var element in dynamicList)
{
Console.Write(element + " ");
}
Console.ReadKey();
} }
}
using System;//8
using System.IO;
using System.Threading;
namespace ћусор{
static class Program
{
static void Main(string[] args)
{
const string targetFolder = @"C:\1";
const string destinationFolder = @"C:\2";
FolderCopier.Perform(targetFolder, destinationFolder);
Console.ReadKey();
} }
static class FolderCopier {
private static int _threadCount = 0;
private static readonly ManualResetEvent ResetEvent = new ManualResetEvent(false);
public static void Perform(string targetFolder, string destinationFolder)
{
var filesPath = Directory.GetFiles(targetFolder, "*.*", SearchOption.AllDirectories);
Interlocked.Exchange(ref _threadCount, filesPath.Length);
foreach (var filePath in filesPath)
{
var files = new Tuple<string, string>(filePath, filePath.Replace(targetFolder, destinationFolder));
ThreadPool.QueueUserWorkItem(CopyFile, files); }
ResetEvent.WaitOne();
ResetEvent.Close();
Console.WriteLine("Files: " + filesPath.Length);
}
private static void CopyFile(object files)
{
var filesTuple = files as Tuple<string, string>;
File.Copy(filesTuple.Item1, filesTuple.Item2, true);
if (Interlocked.Decrement(ref _threadCount) == 0)
{ ResetEvent.Set(); } } } } using System;//11
using System.Linq;
using System.Reflection;
using A;
namespace B
{
[ExportClass]
public class PublicClass1 { }
[ExportClass]
public class PublicClass2 { }
public enum PublicEnum { };
internal class InternalClass { }
}
namespace A
{
static class Program
{
static void ListTypesInAssembly(Assembly assembly)
{
var types = assembly.GetTypes().Where(t => t.IsPublic && t.IsDefined(typeof(ExportClassAttribute), false));
foreach (var type in types)
{
Console.WriteLine(type.FullName);
}
}
static void Main(string[] args)
{
var assemblyPath = Assembly.GetExecutingAssembly().Location;
var assembly = Assembly.LoadFrom(assemblyPath);
ListTypesInAssembly(assembly);
Console.ReadKey();
}
}
[AttributeUsage(AttributeTargets.Class)]
public class ExportClassAttribute : Attribute { }
[ExportClass]
public class PublicClass1 { }
public class PublicClass2 { }
public enum PublicEnum { };
internal class InternalClass { }
} using System;//14
using System.Runtime.InteropServices;
namespace ћусор{
[StructLayout(LayoutKind.Explicit)]
public struct SYSTEM_INFO
{
[FieldOffset(0)]
public Int32 dvOemId;
[FieldOffset(0)]
public Int16 wProcessorArchitecture;
[FieldOffset(2)]
public Int16 wReserved;
[FieldOffset(4)]
public Int32 dwPageSize;
[FieldOffset(8)]
public IntPtr lpMinimumApplicationAddress;
[FieldOffset(12)]
public IntPtr lpMaximumApplicationAddress;
[FieldOffset(16)]
public IntPtr dwActiveProcessorMask;
[FieldOffset(20)]
public Int32 dwNumberOfProcessors;
[FieldOffset(24)]
public Int32 dwProcessorType;
[FieldOffset(28)]
public Int32 dwAllocationGranularity;
[FieldOffset(32)]
public Int32 wProcessorLevel;
[FieldOffset(36)]
public Int16 wProcessorRevision;
}
static class Program {
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.Winapi)]
private static extern void GetNativeSystemInfo(ref SYSTEM_INFO info);
static void Main(string[] args)
{
var info = new SYSTEM_INFO();
GetNativeSystemInfo(ref info);
Console.WriteLine("Number of processors: " + info.dwNumberOfProcessors);
Console.ReadKey(); } }}
using System;//9
using System.Collections.Generic;
using System.Threading;
namespace Мусор{
static class Program {
delegate void FlushCallback(List<object> items);
class ConcurrentAccumulator {
private readonly int _objectLimit;
private readonly int _timeLimit;
private readonly FlushCallback _flushCallback;
private readonly object _sync = new object();
private List<object> _container;
public ConcurrentAccumulator(int objectLimit, int timeLimit, FlushCallback flushCallback) {
_objectLimit = objectLimit;
_timeLimit = timeLimit;
_flushCallback = flushCallback;
_container = new List<object>();
new Thread(Flush).Start(); }
public void Add(object item) {
lock (_sync) {
_container.Add(item);
if (_container.Count >= _objectLimit)
{ Monitor.Pulse(_sync); } } }
private void Flush() {
while (true) {
lock (_sync) {
Monitor.Wait(_sync, _timeLimit);
var oldContainer = _container;
_container = new List<object>();
_flushCallback.BeginInvoke(oldContainer, null, null);
} } } }
private static void FlushCallbackTest(List<object> items) {
Console.WriteLine("FlushCallbackTest in thread #" + Thread.CurrentThread.ManagedThreadId + ", items: " + items.Count);
Thread.Sleep(10000);
Console.WriteLine("FlushCallbackTest in thread #" + Thread.CurrentThread.ManagedThreadId + " finished."); }
static void Main(string[] args) {
var concurrentAccumulator = new ConcurrentAccumulator(3, 3000, FlushCallbackTest);
concurrentAccumulator.Add(new object());
concurrentAccumulator.Add(new object());
Thread.Sleep(4000);
concurrentAccumulator.Add(new object());
concurrentAccumulator.Add(new object());
concurrentAccumulator.Add(new object());
concurrentAccumulator.Add(new object());
Console.ReadKey();
} } } using System;//10
using System.Threading;
namespace ћусор{
delegate void ParallelDelegate();
static class Parallel
{
class Int32Wrapper
{
public Int32Wrapper(int value)
{ Value = value; }
public int Value;
}
public static void WaitAll(ParallelDelegate[] delegates)
{
var resetEvent = new ManualResetEvent(false);
var threadsCountWrapper = new Int32Wrapper(delegates.Length);
foreach (var parallelDelegate in delegates)
{
var info = new Tuple<ParallelDelegate, Int32Wrapper, ManualResetEvent>(parallelDelegate, threadsCountWrapper, resetEvent); ThreadPool.QueueUserWorkItem(ParallelDelegateWrapper, info); }
resetEvent.WaitOne(); }
private static void ParallelDelegateWrapper(object info)
{
var tupleInfo = info as Tuple<ParallelDelegate, Int32Wrapper, ManualResetEvent>;
tupleInfo.Item1();
if (Interlocked.Decrement(ref tupleInfo.Item2.Value) == 0)
{ tupleInfo.Item3.Set(); } } }
static class Program
{
private static void Sleep3()
{
Console.WriteLine("Sleep3: started.");
Thread.Sleep(3000);
Console.WriteLine("Sleep3: finished."); }
private static void Sleep5()
{
Console.WriteLine("Sleep5: started.");
Thread.Sleep(5000);
Console.WriteLine("Sleep5: finished."); }
private static void Sleep7()
{
Console.WriteLine("Sleep7: started.");
Thread.Sleep(7000);
Console.WriteLine("Sleep7: finished."); }
static void Main(string[] args)
{
Parallel.WaitAll(new ParallelDelegate[] { Sleep3, Sleep5, Sleep7 });
Console.WriteLine("Program: finished.");
Console.ReadKey(); } using System;//13
using System.IO;
using System.Threading;
namespace ћусор{
static class FileUtils {
private const int BlockSize = 1024 * 1024;
public static void CopyFile(string targetPath, string destinationPath, CancellationTokenSource copyCancellationToken,
CancellationTokenSource waitCancellationToken)
{
var readStream = new FileStream(targetPath, FileMode.Open, FileAccess.Read, FileShare.Read, BlockSize * 2, true);
var writeStream = new FileStream(destinationPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write, BlockSize * 2, true);
var bytesRead = 0;
var buffer = new byte[BlockSize];
do
{
var result = readStream.BeginRead(buffer, 0, buffer.Length, null, null);
if (copyCancellationToken.IsCancellationRequested)
{
readStream.EndRead(result);
readStream.Close();
writeStream.Close();
File.Delete(destinationPath);
return;
}
bytesRead = readStream.EndRead(result);
writeStream.Write(buffer, 0, bytesRead);
} while (bytesRead == BlockSize);
readStream.Close();
writeStream.Close();
waitCancellationToken.Cancel(); } }
static class Program
{
static void Main(string[] args)
{
var copyCancellationToken = new CancellationTokenSource();
var waitCancellationToken = new CancellationTokenSource();
var thread =
new Thread(() => FileUtils.CopyFile(@"D:\1", @"D:\2", copyCancellationToken, waitCancellationToken));
thread.Start();
while (!copyCancellationToken.IsCancellationRequested && !waitCancellationToken.IsCancellationRequested)
{
if (Console.KeyAvailable)
{
Console.ReadKey();
copyCancellationToken.Cancel(); }
else
{ Thread.Sleep(50); } }
thread.Join(); Console.Out.WriteLine(waitCancellationToken.IsCancellationRequested ? "Copy: successful" : "Copy: terminated");
Console.ReadKey();
} }}
using System;//15
using System.Linq;
namespace ћусор{
static class ArrayHelper {
public static unsafe int Sum(int[] array, int size)
{
var result = 0;
checked
{
fixed (int* p = array)
{
for (var i = 0; i < size; i++)
{
result += *(p + i); } } }
return result; } }
class Program
{
static void Main(string[] args)
{
var test1 = Enumerable.Range(1, 100).ToArray();
var test2 = Enumerable.Range(Int32.MaxValue / 2, 100).ToArray();
try
{
Console.WriteLine("test1 sum = " + ArrayHelper.Sum(test1, 100));
Console.WriteLine("test2 sum = " + ArrayHelper.Sum(test2, 100)); }
catch (OverflowException)
{ Console.WriteLine("OverflowException.");}
Console.ReadKey(); } } }

Приложенные файлы

  • docx 19049324
    Размер файла: 31 kB Загрузок: 0

Добавить комментарий