Task doesn't work parallel - c#

I have two task which work as producer and consumer, but they don't run in parallel. Second one waits for the first one to compelete. Can you explain why and how can I correct this? I want both of them run at the same time. (I try many varians, but all of them don't work well)
class DirectoryReader
{
private readonly string _dir ;
private Processor[] _processors;
private string[] _files;
private readonly Regex _rx = new Regex(#"([^.\\]+)\.cs");
private Queue<Processor> queue = new Queue<Processor>();
private bool isOff;
private AutoResetEvent isAvailable = new AutoResetEvent(false);
private StreamWriter log = new StreamWriter("Log.txt");
public DirectoryReader(string dir)
{
_dir = dir;
}
public Container[] ProcessAllFiles()
{
_files = Directory.GetFiles(_dir, "*.cs", SearchOption.AllDirectories);
_processors = new Processor[_files.Length];
var thread = Task.Run(() => Compute());
var thread2 = Task.Run(() => Read());
thread.Wait();
}
public void Read()
{
for (var i = 0; i < _files.Length; i++)
{
try
{
var matches = _rx.Matches(_files[i]);
foreach (var match in matches)
{
//Console.WriteLine(match);
lock (log)
{
log.WriteLine(match);
}
}
_processors[i] = new Processor(matches[matches.Count - 1].ToString(), File.ReadAllText(_files[i]));
lock (queue)
{
queue.Enqueue(_processors[i]);
isAvailable.Set();
}
}
catch (IOException ex)
{
Console.WriteLine(ex.Message + _files[i]);
}
}
isOff = true;
}
public void Compute()
{
Processor proc = null;
int ccount = 0;
while (true)
{
lock (queue)
{
if ((ccount = queue.Count) > 0)
{
proc = queue.Dequeue();
}
}
if (ccount == 0)
{
if (isOff)
{
return;
}
else
{
isAvailable.WaitOne();
}
}
if (proc != null)
{
//Some calculations on proc
lock (log)
{
log.WriteLine("+++++" + proc.FileName);
}
}
}
}
}
UPD1: I rewrite this code with using BlockingCollection, but is still doesn't work correct
class DirectoryReader
{
private readonly string _dir ;
private Processor[] _processors;
private string[] _files;
private readonly Regex _rx = new Regex(#"([^.\\]+)\.cs");
private List<Container> answer = new List<Container>();
BlockingCollection<FileContainer> dataItems = new BlockingCollection<FileContainer>();
public DirectoryReader(string dir)
{
_dir = dir;
}
public void ProcessAllFiles()
{
_files = Directory.GetFiles(_dir, "*.cs", SearchOption.AllDirectories);
_processors = new Processor[_files.Length];
var task = Task.Factory.StartNew(Compute);
var task2 = Task.Factory.StartNew(Read);
Task.WaitAll(task, task2);
}
public void Read()
{
for (var i = 0; i < _files.Length; i++)
{
try
{
var matches = _rx.Matches(_files[i]);
dataItems.Add(new FileContainer{
Name = matches[matches.Count - 1].ToString(),
Content = File.ReadAllText(_files[i])});
}
catch (IOException ex)
{
Console.WriteLine(ex.Message + _files[i]);
}
}
dataItems.CompleteAdding();
}
public void Compute()
{
FileContainer proc = null;
while (!dataItems.IsCompleted)
{
try
{
proc = dataItems.Take();
}
catch (InvalidOperationException) { }
if (proc != null)
{
//Some calculations
}
}
}
}

Related

Timer in SignalR overlaps when another group enters into hub

I have created a signalR hub which is solving purpose to show timer at UI of grouped person. If one person starts a play with another one, timer runs very nice.
But the problem is when another group start a new play and previous one is still in progress, I mean Timer is already running, then it overlaps the timer and hold one group. Timer runs once at a time. But I want it to have threading and run for every group.
here is my code:
ConnectionMapping.cs
public class ConnectionMapping<T>
{
private readonly Dictionary<T, HashSet<string>> _connections = new Dictionary<T, HashSet<string>>();
public int Count { get { return _connections.Count; } }
public void Add(T key, string connectionId)
{
lock (_connections)
{
HashSet<string> connections;
if (!_connections.TryGetValue(key, out connections))
{
connections = new HashSet<string>();
_connections.Add(key, connections);
}
lock (connections)
{
connections.Add(connectionId);
}
}
}
public IEnumerable<string> GetConnections(T key)
{
HashSet<string> connections;
if (_connections.TryGetValue(key, out connections))
{
return connections;
}
return Enumerable.Empty<string>();
}
public void Remove(T key, string connectionId)
{
lock (_connections)
{
HashSet<string> connections;
if (!_connections.TryGetValue(key, out connections))
{
return;
}
lock (connections)
{
connections.Remove(connectionId);
if (connections.Count == 0)
{
_connections.Remove(key);
}
}
}
}
}
Below is a Hub class:
public class TimeSyncingHub : Hub
{
private readonly static ConnectionMapping<int> _connections = new ConnectionMapping<int>();
private readonly PlayerPickTicker _playerPickTicker;
private readonly object _PickStateLock = new object();
private IUserBusiness userBusiness;
public TimeSyncingHub() :
this(PlayerPickTicker.Instance)
{
}
public TimeSyncingHub(PlayerPickTicker playerPickTicker)
{
_playerPickTicker = playerPickTicker;
}
public Task LeaveRoom(string roomName)
{
return Groups.Remove(Context.ConnectionId, roomName);
}
public async Task JoinRoom(string roomName)
{
await Groups.Add(Context.ConnectionId, roomName);
Clients.Group(roomName).JoinedRoom("Enter into group - " + roomName);
}
}
Another class where I have written time code is PlayerPickTicker class which is depends in same and implemented in constructor of hub class as shown in class above.
Below is PlayerPickTicker class:
public class PlayerPickTicker : IDisposable
{
private readonly static Lazy<PlayerPickTicker> _instance = new Lazy<PlayerPickTicker>(
() => new PlayerPickTicker(GlobalHost.ConnectionManager.GetHubContext<TimeSyncingHub>()));
private IHubContext _context;
public UserPlayerPickModel UserPlayerPick { get; set; }
public static PlayerPickTicker Instance { get { return _instance.Value; } }
private Timer TickTimer;
private Timer InitialTickTimer;
public int StartSeconds { get; set; }
public int StopSeconds { get; set; }
public bool IsTimerOver { get; set; }
private PlayerPickTicker(IHubContext context)
{
_context = context;
}
public void StartInitialTimer(Model.QueryModel queryModel)
{
try
{
MyDraftBusiness myDraft = new MyDraftBusiness();
myDraft.UdpatePlaysOneMinuteTimerPending(queryModel);
//lock (_InitialTimerStateLock)
//{
//StartSeconds = 60;
//if (InitialTickTimer != null)
//{
// InitialTickTimer.Dispose();
//}
States = new Dictionary<string, bool>() {
{ "IsInitialTimerOver", false},
{ "CallInitialTimerOverMethod", true},
};
PickPlayer = new Dictionary<string, long>() { { "LastPlayerPickId", 0 } };
//lock (States)
//{
StartSeconds = 60;
StopSeconds = 0;
IsInitialTimerOver = false;
CallInitialTimerOverMethod = true;
//}
InitialTickTimer = new Timer();// OnTimerElapsedInitialTimer, queryModel, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
InitialTickTimer.Interval = 1000;
InitialTickTimer.Enabled = true;
InitialTickTimer.Elapsed += (sender, e) => OnTimerElapsedInitialTimer(queryModel, e);
InitialTickTimer.AutoReset = false;
//}
//}
}
catch (Exception ex)
{
Helpers.ExceptionsLog.LogFile(" -( At StartInitialTimer Mehtod )- " + ex.Message);
}
}
private void OnTimerElapsedInitialTimer(object sender, ElapsedEventArgs e)
{
Model.QueryModel queryModel = (Model.QueryModel)sender;
try
{
//lock (_InitialtickStateLock)
//{
var states = (Dictionary<string, bool>)States;
var IsInitialTimerOver = states.FirstOrDefault(x => x.Key == "IsInitialTimerOver").Value;
//Clients.
if (StartSeconds <= StopSeconds && !IsInitialTimerOver)
{
if (InitialTickTimer != null)
{
InitialTickTimer.Dispose();
}
//IsInitialTimerOver = true;
states["IsInitialTimerOver"] = true;
//lock (States)
//{
//************** from client to server
var JsonResult = new JObject();
JsonResult.Add("data", JToken.FromObject(queryModel));
string GroupName = "Group" + queryModel.playId.ToString();
_context.Clients.Group(GroupName).initialTimerCompleted(JsonResult);
//_context.Clients.Group(GroupName, _context.Clients.All).initialTimerCompleted(JsonResult);
//_context.Clients.All.initialTimerCompleted(JsonResult);
MyDraftBusiness myDraft = new MyDraftBusiness();
try
{
myDraft.UdpatePlaysOneMinuteTimerRunning(queryModel);
DraftModel draftModel = myDraft.GetDraftById(queryModel);
if (draftModel != null)
{
var userPlayerPicks = myDraft.GetUserPlayerPickByPlayId(draftModel.PlayId);
if (draftModel.IsDraftFilled)
{
if (draftModel.Play != null && draftModel.Play.IsOneMinuteTimerPending == true)
{
myDraft.UdpatePlaysOneMinuteTimerPending(queryModel);
}
else
{
var activeUserPick = userPlayerPicks.Where(x => !x.Picked).FirstOrDefault();
if (activeUserPick != null)
{
StartTimer(activeUserPick);
}
}
}
}
}
catch (Exception ex)
{
Helpers.ExceptionsLog.LogFile(" -( At OnTimerElapsedInitialTimer Mehtod inner catch )- " + ex.Message);
var userPlayerPicks = myDraft.GetUserPlayerPickByPlayId(queryModel.playId);
var activeUserPick = userPlayerPicks.Where(x => !x.Picked).FirstOrDefault();
if (activeUserPick != null)
{
StartTimer(activeUserPick);
}
}
//}
}
else if (StartSeconds > 0)
{
//IsInitialTimerOver = false;
states["IsInitialTimerOver"] = false;
//lock (States)
//{
StartSeconds -= 1;
var GroupName = "Group" + Convert.ToString(queryModel.playId);
_context.Clients.Group(GroupName).intialTimerElapsed(StartSeconds);
_context.Clients.All.pickRunning(queryModel.playId);
InitialTickTimer.Stop();
InitialTickTimer.Start();
//StartInitialTimer(queryModel);
//}
}
//}
}
catch (Exception ex)
{
Helpers.ExceptionsLog.LogFile(" -( At OnTimerElapsedInitialTimer Mehtod )- " + ex.Message);
}
}
I know it's big code and hard to understand. But I hope for Any Good Developer here, Much appreciation for helper from core of my heart!

Memory exception HashSet

I get an memory exception while loading a 4GB file. i have to do that twice but i have enougth memmory to load them. the memmory exception occures when i have 3gb left or more.:(.
Method:
public TableModel LoadTable(string path) {
TableModel model = new TableModel();
using (FileStream filestream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8)) {
string line = "";
bool isHeader = true;
int counter = 0;
List<string> rows = new List<string>();
while ((line = reader.ReadLine()) != null) {
if (isHeader) {
model.Columns = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
isHeader = false;
continue;
} else {
if (Settings.Default.RonudSet != 0) {
rows.Add(RoundDecimals(line));
} else {
rows.Add(line);
}
}
counter++;
}
model.RowCount = counter;
model.ColumnsCount = model.Columns.Length;
model.Keys = new HashSet<string>(rows);
}
}
return model;
}
Exception:
System.OutOfMemoryException was unhandled
The function evaluation was disabled because of an out of memory exception.
TableModel:
class TableModel {
private string tableName;
private string[] columns;
private HashSet<string> keys;
public int ColumnsCount { get; set; }
public int RowCount { get; set; }
public string TableName { get { return tableName; } set { this.tableName = value; } }
public string[] Columns { get { return columns; } set { this.columns = value; } }
public HashSet<string> Keys { get { return keys; } set { this.keys = value; } }
}
Start Compare:
if (newFile.Name.Equals(currFile.Name)) {
FileLoader loader = new FileLoader();
TableModel newModel = loader.LoadTable(newFile.ToString());
TableModel currentModel = loader.LoadTable(currFile.ToString());
newModel.TableName = newFile.Name;
currentModel.TableName = currFile.Name;
new Compare(newModel, currentModel, currFile.Directory.Name);
break;
}
Compare:
private void CheckColumns() {
bool sameColumnCount = CheckColumnsCount();
int counter = 0;
currentContent = new HashSet<string>(currentModel.Columns);
newContent = new HashSet<string>(newModel.Columns);
foreach (string header in currentContent) {
if (!newContent.Contains(header)) {
headersNotFoundInN.Add(header);
}
}
foreach (string header in newContent) {
if (!currentContent.Contains(header)) {
headersNotFoundInC.Add(header);
}
}
if (currentModel.ColumnsCount == newModel.ColumnsCount) {
for (int i = 0; i < currentModel.ColumnsCount; i++) {
if (currentModel.Columns[i] == newModel.Columns[i]) {
counter++;
}
}
if (counter == currentModel.ColumnsCount) {
headerSequence = true;
} else {
headerSequence = false;
}
} else {
headerSequence = false;
}
bool emptyNotFoundIn = false;
if (headersNotFoundInC.Count == 0 && headersNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameColumnCount, headerSequence, emptyNotFoundIn);
}
private void CheckRows() {
bool sameRowCount = CheckRowCount();
currentContent = new HashSet<string>(currentModel.Keys);
newContent = new HashSet<string>(newModel.Keys);
foreach (string key in currentContent) {
if (!newContent.Contains(key)) {
rowNotFoundInN.Add(key);
}
}
foreach (string key in newContent) {
if (!currentContent.Contains(key)) {
rowNotFoundInC.Add(key);
}
}
bool emptyNotFoundIn = false;
if (rowNotFoundInC.Count == 0 && rowNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameRowCount, emptyNotFoundIn);
}
Its a table with many rows that i have to compare with a similar table. at the end i have to give a report about the diffrences. but i fail here where i have to load this massive file.
try using BufferedStream
using (BufferedStream bs = new BufferedStream(filestream))
{
}

After catching an error in a Try Catch, how can I return to the loop and keep searching the C drive?

I'm searching the C Drive for MP3 files using Directory.GetFiles (All Directories) but when it comes to searching the Recycle Bin I get and access error. I use a Try Catch to catch it. What I'm wondering is how to disreguard the error and continue searching the drive. Here's my code...
private void toolStripButtonSearch_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialogMain.ShowDialog();
if(result == DialogResult.OK)
{
try
{
foreach (String file in Directory.GetFiles(folderBrowserDialogMain.SelectedPath, "*.mp3", SearchOption.AllDirectories))
{
FileInfo fi = new FileInfo(file);
ListViewItem lvi = new ListViewItem(fi.Name);
listViewMain.Items.Add(lvi);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Here is a way how it can be done:
IEnumerable<string> GetAllFiles(string path, string pattern)
{
IEnumerable<string> files = null;
try
{
files = Directory.GetFiles(path, pattern);
}
catch (UnauthorizedAccessException) { }
if (files == null) yield break;
foreach (var fname in files) yield return fname;
foreach (var dname in Directory.GetDirectories(path))
{
foreach (var fname in GetAllFiles(dname, pattern)) yield return fname;
}
}
and invoke it as
var allMP3s = GetAllFiles(#"c:\", "*.mp3" ).ToList();
One method of catching any errors enumerating a folder within a drive that maintains the ability to late evaluate the directory contents, is to fire events, then enumerates over the events. This avoids the issue with having a yield return block inside a try and catch block.
Please see example method.
public class DirectoryEnumerator
{
public class FileEventArgs : EventArgs
{
public FileInfo FileInfo { get; }
public FileEventArgs(FileInfo fileInfo)
{
FileInfo = fileInfo;
}
}
public class DirectoryEventArgs : EventArgs
{
public DirectoryInfo DirectoryInfo { get; }
public DirectoryEventArgs(DirectoryInfo directoryInfo)
{
DirectoryInfo = directoryInfo;
}
}
public class EventEnumerator<T> : IEnumerable<T>, IEnumerator<T>
{
private readonly Queue<T> _queue = new Queue<T>();
private readonly ManualResetEvent _event;
public bool Started { get; set; }
public EventEnumerator()
{
_event = new ManualResetEvent(false);
}
public void Action(Action action)
{
Task.Run(() => action.Invoke()).ContinueWith(task => { MarkComplete(); });
}
public void Callback(T value)
{
Started = true;
lock (_queue)
{
_queue.Enqueue(value);
_event.Set();
}
}
public void MarkComplete()
{
Started = false;
_event.Set();
}
public void Dispose()
{
}
public bool MoveNext()
{
_event.WaitOne();
var notComplete = IsNotComplete();
if (notComplete)
{
lock (_queue)
{
Current = _queue.Dequeue();
if (_queue.Count == 0)
_event.Reset();
}
}
return IsNotComplete();
}
private bool IsNotComplete()
{
return _queue.Count > 0 || Started;
}
public void Reset()
{
lock (_queue)
{
_queue.Clear();
}
}
public T Current { get; private set; }
object IEnumerator.Current
{
get { return Current; }
}
public IEnumerator<T> GetEnumerator()
{
while (this.MoveNext())
{
if (Current != null)
{
yield return this.Current;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public DirectoryEnumerator()
{
}
public event EventHandler OnNewFile;
private void ProcessFile(FileInfo path)
{
OnNewFile?.Invoke(this, new FileEventArgs(path));
}
public event EventHandler OnNewDirectory;
private void ProcessDirectory(DirectoryInfo path)
{
OnNewDirectory?.Invoke(this, new DirectoryEventArgs(path));
}
public static IEnumerable<FileInfo> GetFiles(DirectoryInfo directoryInfo, bool recurse = true)
{
var directoryEnumerator = new DirectoryEnumerator();
var eventEnumeratingEnumerable = new EventEnumerator<FileInfo>();
eventEnumeratingEnumerable.Action(() => { directoryEnumerator.Enumerate(directoryInfo, recurse); });
directoryEnumerator.OnNewFile +=
(sender, eventHandler) =>
{
eventEnumeratingEnumerable.Callback(((FileEventArgs)eventHandler).FileInfo);
};
return eventEnumeratingEnumerable;
}
public static IEnumerable<DirectoryInfo> GetDirectories(DirectoryInfo directoryInfo, bool recurse = true)
{
var directoryEnumerator = new DirectoryEnumerator();
var eventEnumeratingEnumerable = new EventEnumerator<DirectoryInfo>();
eventEnumeratingEnumerable.Action(() => { directoryEnumerator.Enumerate(directoryInfo, recurse); });
directoryEnumerator.OnNewDirectory +=
(sender, eventHandler) =>
{
eventEnumeratingEnumerable.Callback(((DirectoryEventArgs) eventHandler).DirectoryInfo);
};
return eventEnumeratingEnumerable;
}
public void Enumerate(DirectoryInfo directoryInfo, bool recurse = true)
{
Enumerate(directoryInfo, recurse, ProcessFile, ProcessDirectory);
}
private void Enumerate(DirectoryInfo directoryInfo, bool recurse, Action<FileInfo> fileAction, Action<DirectoryInfo> directoryAction)
{
TryEnumerateFiles(directoryInfo, fileAction);
TryEnumerateDirectories(directoryInfo, recurse, fileAction, directoryAction);
}
private void TryEnumerateDirectories(DirectoryInfo directoryInfo, bool recurse, Action<FileInfo> fileAction, Action<DirectoryInfo> directoryAction)
{
try
{
foreach (var subDir in directoryInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly))
{
if (directoryAction != null)
{
directoryAction(subDir);
}
if (recurse)
{
Enumerate(subDir, true, fileAction, directoryAction);
}
}
}
catch (Exception ex)
{
Logger.Debug($"Failed to enumerate subdirectories within directory {directoryInfo.FullName}", ex);
}
}
private void TryEnumerateFiles(DirectoryInfo directoryInfo, Action<FileInfo> fileAction)
{
try
{
foreach (var file in directoryInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly))
{
if (fileAction != null)
{
fileAction(file);
}
}
}
catch (Exception ex)
{
Logger.Debug($"Failed to enumerate files within directory {directoryInfo.FullName}", ex);
}
}
private static void Examples()
{
// Recursive file enumeration
var files1 = DirectoryEnumerator.GetFiles(new DirectoryInfo("C:\\")).ToList();
// File enumeration
var files2 = DirectoryEnumerator.GetFiles(new DirectoryInfo("C:\\"), false).ToList();
// Recursive directory enumeration
var directory1 = DirectoryEnumerator.GetDirectories(new DirectoryInfo("C:\\")).ToList();
// Directory enumeration
var directory2 = DirectoryEnumerator.GetDirectories(new DirectoryInfo("C:\\"), false).ToList();
// Event enumeration
var directoryEnumerator = new DirectoryEnumerator();
directoryEnumerator.OnNewFile += (sender, file) => {
// dosomething
};
directoryEnumerator.OnNewDirectory += (sender, file) => {
// dosomething
};
directoryEnumerator.Enumerate(new DirectoryInfo("C:\\"), false);
}
}

Directory created by C# program thread is locked

I have this program that creates threads on which i must create queue folders and
check them for files.
Now I noticed my program failed after processing a huge number of files without problems.
I produces a UnauthorizedAccessException so I went looking for that folder and it appears
the folder has been locked out totally?!
Could this be my anti-virus blocking access or is it something I must fix on my thread?
public class worker
{
public bool Stopping = false;
private System.Timers.Timer _timer;
private List<string> _files;
#region Feedback
public event FeedbackHandler Feedback;
public delegate void FeedbackHandler(object sender, string text);
#endregion
#region Properties
private string _name;
public string Name
{
get { return _name; }
}
private string _folder;
public string Folder
{
get { return _folder; }
set { _folder = value; }
}
private string _outfolder = Path.Combine(shared.Root, "out");
public string Outfolder
{
get { return _outfolder; }
set { _outfolder = value; }
}
private string _backupfolder = Path.Combine(shared.Root, "backup");
public string Backupfolder
{
get { return _backupfolder; }
set { _backupfolder = value; }
}
private string _filter = "*.*";
public string Filter
{
get { return _filter; }
set { _filter = value; }
}
private SearchOption _subfolders = SearchOption.TopDirectoryOnly;
public bool Subfolders
{
get { return (_subfolders == SearchOption.AllDirectories); }
set { if (value) { _subfolders = SearchOption.AllDirectories; } else { _subfolders = SearchOption.TopDirectoryOnly; } }
}
#endregion
#region Constructor
public worker(string Name)
{
_name = Name;
_folder = Path.Combine(shared.Root, "queues");
_folder = Path.Combine(_folder, Name);
}
#endregion
#region Destructor
~worker()
{
}
#endregion
#region Control
public void Start()
{
Stopping = false;
Directory.CreateDirectory(_folder);
_timer = new System.Timers.Timer(1);
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
Feedback(this, "[" + _name + "] started!");
}
public void Stop()
{
Stopping = true;
Feedback(this, "[" + _name + "] stopped...");
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (Stopping)
{
_timer.Stop();
_files.Clear();
return;
}
_timer.Stop();
Process();
_timer.Start();
}
#endregion
void Process()
{
if (Directory.Exists(_folder))
{
_files = Directory.GetFiles(_folder, _filter, _subfolders).ToList();
foreach (string _file in _files.ToArray())
{
if (Stopping) { break; }
document _document = new document(_file);
_document.Copy(_backupfolder);
_document.Move(_outfolder);
}
_files = new List<string>();
}
}
}
public class document
{
private string _header;
#region Feedback
public event FeedbackHandler Feedback;
public delegate void FeedbackHandler(object sender, string text);
#endregion
#region Properties
private string _file;
public string File
{
get { return _file; }
}
private job _job;
public job Job
{
get { return _job; }
}
#endregion
#region Constructor
public document(string File)
{
_file = File;
_header = shared.FileOperations.ReadHeader(_file);
_job = new job(_file, _header);
_job.ReadHeader();
}
#endregion Constructor
public void Copy(string Folder)
{
string _backupfile;
_backupfile = Path.Combine(Folder,_job.Name);
_backupfile = Path.Combine(_backupfile,_job.Company);
_backupfile = Path.Combine(_backupfile, DateTime.Now.ToString("yyyy"));
_backupfile = Path.Combine(_backupfile, DateTime.Now.ToString("MMMM"));
Directory.CreateDirectory(_backupfile);
_backupfile = Path.Combine(_backupfile, Path.GetFileName(_file));
shared.FileOperations.CopyFile(_file, _backupfile, true);
}
public void Move(string Folder)
{
string _outfile;
_outfile = Path.Combine(Folder, Path.GetFileNameWithoutExtension(_file));
shared.FileOperations.MoveFile(_file, _outfile, true);
}
}
public struct shared
{
public static string Root
{
get
{
string _base = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
return Directory.GetParent(_base).Parent.FullName.ToString();
}
}
public struct Patterns
{
public const string Header = #"\^?JOB\s(?<JOB>[a-zA-Z0-9]+[0-9]{3})[D]?(?<ACTION>[JFE]+)(?<COMPANY>[A-Z]{2,2})\s" +
#"(?<EMAIL>-emto=.*)?" +
#"-C(?<COPIES>[0-9]{2,2})\s" +
#"-Z""(?<PRINTER>[A-Z0-9]+)""\s" +
#"(?:\^?PAGE 01|(?<FAX>\^?FAX.*)\s\^?PAGE 01?)";
public const string Jump = #"\^PAGE\s[0-9]+";
public const string Pages = #"(\$?PAGE\s)";
public const string Fax = #"\^?FAX FROM_COMPANY\s""(?<FROM>.*)""\s" +
#"\^?FAX FROM_FAX_NUM\s""(?<FFAX>.*)""\s" +
#"\^?FAX FROM_NAME\s""(?<FNAME>.*)""\s" +
#"\^?FAX TO_FAX_NUM\s""(?<TFAX>.*)""\s" +
#"\^?FAX TO_COMPANY\s""(?<TO>.*)""\s" +
#"\^?FAX TO_NAME\s""(?<TNAME>.*)""\s" +
#"\^?FAX WHO\s""(?<WHO>.*)""\s" +
#"\^?FAX ID\s+(?<ID>.*)";
public const string Mail = #"-em([^\s=]+)=(""[^""]*""|[^\s]+)";
public const string Seperator = #"^";
}
public struct FileOperations
{
// Encoding
public static Encoding ReadEncoding = Encoding.GetEncoding(1252);
public static Encoding WriteEncoding = Encoding.UTF8;
// Timeouts
static int Timeout = 1;
static int FileTimeout = 10000; // 10 seconds/file permitted..
// Header
public static string ReadHeader(string SourceFile)
{
return ReadHeader(SourceFile, Patterns.Jump);
}
public static string ReadHeader(string SourceFile, string Beacon)
{
WaitFile(SourceFile);
string r = null;
string l = null;
try
{
StreamReader _reader = new StreamReader(SourceFile, ReadEncoding);
Match _match;
do
{
l = _reader.ReadLine();
r += l + " ";
_match = Regex.Match(l, Beacon);
} while (!_match.Success);
_reader.Close();
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
return r;
}
// Read Contents
public static List<string> ReadFile(string SourceFile)
{
return ReadFile(SourceFile, Patterns.Seperator);
}
public static List<string> ReadFile(string SourceFile, string Seperator)
{
WaitFile(SourceFile);
List<string> lines = new List<string>();
try
{
StreamReader sr = new StreamReader(SourceFile, Encoding.GetEncoding(1250));
string tmp = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
if (!string.IsNullOrEmpty(line) && line.Substring(0, 1) == Seperator)
{
if (!string.IsNullOrEmpty(tmp))
{
lines.Add(tmp);
}
tmp = line.Replace(Seperator, "^");
}
else
{
tmp += Environment.NewLine + line;
}
}
sr.Close();
if (!string.IsNullOrEmpty(tmp))
{
lines.Add(tmp);
}
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) {throw ex;}
}
return lines;
}
// Write Contents
public static void WriteFile(string DestinationFile, List<string> Lines)
{
try
{
File.WriteAllLines(DestinationFile, Lines.ToArray(), WriteEncoding);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
public static void WriteFile(string DestinationFile, string Contents)
{
try
{
File.WriteAllText(DestinationFile, Contents);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
// Move File
public static void MoveFile(string SourceFile, string DestinationFile, bool Overwrite)
{
WaitFile(SourceFile);
try
{
string _count = null;
string _destination = Path.GetDirectoryName(DestinationFile);
string _file = Path.GetFileNameWithoutExtension(DestinationFile);
string _extension = Path.GetExtension(DestinationFile);
string[] _files = Directory.GetFiles(_destination, _file + "*");
if (_files.Length > 0)
{
if (Overwrite)
{
for (int x = 0; x <= _files.Length - 1; x++)
{
File.Delete(_files[x]);
}
}
else
{
_count = "_" + (_files.Length - 1).ToString("D4");
}
}
DestinationFile = Path.Combine(_destination, _file + _count + _extension);
File.Move(SourceFile, DestinationFile);
}
catch (Exception ex)
{
if (Debugger.IsAttached) { throw ex; }
}
}
public static void CopyFile(string SourceFile, string DestinationFile, bool Overwrite)
{
WaitFile(SourceFile);
try
{
string _count = null;
string _destination = Path.GetDirectoryName(DestinationFile);
string _file = Path.GetFileNameWithoutExtension(DestinationFile);
string _extension = Path.GetExtension(DestinationFile);
string[] _files = Directory.GetFiles(_destination, _file + "*");
if (_files.Length > 0)
{
if (Overwrite)
{
for (int x = 0; x <= _files.Length - 1; x++)
{
File.Delete(_files[x]);
}
}
else
{
_count = "_" + (_files.Length - 1).ToString("D4");
}
}
DestinationFile = Path.Combine(_destination, _file + _count + _extension);
File.Copy(SourceFile, DestinationFile);
}
catch (Exception ex)
{
if (Debugger.IsAttached) { throw ex; }
}
}
// Delete File
public static void DeleteFile(string SourceFile)
{
WaitFile(SourceFile);
try
{
File.Delete(SourceFile);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
// Check File
static void WaitFile(string SourceFile)
{
Timeout = 1;
while (!File.Exists(SourceFile))
{
System.Threading.Thread.Sleep(Timeout);
Timeout++;
if (Timeout == FileTimeout)
{
// todo
if (Debugger.IsAttached) { throw new Exception("Timout exceeded!"); }
}
}
Timeout = 1;
while (!IsFileReady(SourceFile))
{
System.Threading.Thread.Sleep(Timeout);
Timeout++;
if (Timeout == FileTimeout)
{
// todo
if (Debugger.IsAttached) { throw new Exception("Timout exceeded!"); }
}
}
}
static bool IsFileReady(String SourceFile)
{
try
{
using (FileStream inputStream = File.Open(SourceFile, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
}
public struct Functions
{
public static string CleanXML(string Text)
{
Text = Text.Replace(#"&", #"&");
Text = Text.Replace(#"<", #"<");
Text = Text.Replace(#">", #">");
Text = Text.Replace(#"""", #""");
Text = Text.Replace(#"'", #"&apos;");
return Text;
}
}
}
void Work(string Name)
{
_worker = _workers.FirstOrDefault(w => w.Name == Name);
if (_worker == null)
{
_worker = new worker(Name);
_worker.Feedback+=new worker.FeedbackHandler(Feedback);
_worker.Folder = Path.Combine(_queuefolder, Name);
_worker.Outfolder = _outfolder;
_worker.Backupfolder = _backupfolder;
_workers.Add(_worker);
Thread _thread = new Thread(_worker.Start);
_thread.Start();
_thread.Join();
}
}
To clarify what i meant:
//worker class
private volatile bool _stopping;
private Thread _thread;
public void Start()
{
_stopping = false;
Directory.CreateDirectory(_folder);
_thread = new Thread(Process);
_thread.Start();
Feedback(this, "[" + _name + "] started!");
}
public void Stop()
{
_stopping = true;
_thread.Join();
Feedback(this, "[" + _name + "] stopped...");
}
private void Process()
{
while(!_stopping)
{
......
Thread.Sleep(100);
}
}
Because the way you are using timers... It's wrong. And while its interesting to know, why windows locks the folder, you should start from doing some refactoring. It might actually solve your problem along the way.

C# multi-thread ping

I'm working on a network monitoring application, that pings a (not known) number of hosts. So far I have the code below. I've made a class PingHost with a function zping and I called it with the help of a timer once every 2 seconds to let the 2 pings to finish, even if one of them gets TimedOut. But I think a better solution is to generate a new thread for every ping, so that the ping of every host would be independent.
Can anyone give me a hint how to do this?
namespace pinguin
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
PingHost caca = new PingHost();
PingHost caca1 = new PingHost();
this.label1.Text = caca.zping("89.115.14.160");
this.label2.Text = caca1.zping("89.115.14.129");
}
}
public class PingHost
{
public string zping(string dest)
{
Application.DoEvents();
Ping sender = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 50;
int failed = 0;
int pingAmount = 5;
string stat = "";
PingReply reply = sender.Send(dest, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
stat = "ok";
}
else
{
stat = "not ok!";
}
return stat;
}
}
}
If you use .NET 4 you can use Parallel.Invoke.
You could handle the Ping.PingCompleted event:
ping.PingCompleted += new PingCompletedEventHandler(ping_PingCompleted);
then use:
ping.SendAsync()
side note: Choose more suitable names for your classes and routines. PingHost is more suitable as a routine name
Once I wrote such a solution (it constantly pings about 300 machines):
public class ManyAdressPing {
private readonly bool bAutoStarted;
private readonly CancellationTokenSource cancel = new CancellationTokenSource();
public ConcurrentDictionary<IPAddress, OneAddressPing> pingi = new ConcurrentDictionary<IPAddress, OneAddressPing>();
public ManyAdressPing(bool AutoStarted = true) {
bAutoStarted = AutoStarted;
}
public int CountPings => pingi.Count;
public void AddPingAddress(IPAddress addr, int msTimeOut = 3000, int BetweenPing = 3000) {
var oap = new OneAddressPing(addr, cancel.Token, msTimeOut, BetweenPing);
if (bAutoStarted) oap.Start();
pingi.TryAdd(oap.ipAddress, oap);
}
public void RemovePingAddress(IPAddress addr) {
if (pingi.TryRemove(addr, out var p)) p.Stop();
}
public void Stop() {
cancel.Cancel();
foreach (var pair in pingi) pair.Value.Stop();
}
public PingReply GetReply(IPAddress addr) {
if (pingi.ContainsKey(addr)) return pingi[addr].GetReply();
return null;
}
public Tuple<long, long> GetSuccessOperation(IPAddress addr) {
if (pingi.ContainsKey(addr)) return pingi[addr].GetSuccessOperation();
return null;
}
public PingReply[] GetReply() {
PingReply[] ret = pingi.Values.Select(x=>x.GetReply()).ToArray();
return ret;
}
public PingInfo GetPingInfo(IPAddress addr) {
if (pingi.ContainsKey(addr)) {
var ret = new PingInfo();
var p = pingi[addr];
ret.reply = p.GetReply();
ret.SuccessPing = p._SuccessReply;
ret.FailPing = p._FailReply;
ret.LastSuccessPing = p.LastSuccessfullPing;
return ret;
}
return null;
}
public bool IsPinged(IPAddress addr) {
if (pingi.ContainsKey(addr)) return true;
return false;
}
public IPAddress[] GetAddressesPing() {
return pingi.Keys.ToArray();
}
}
public class PingInfo {
public PingReply reply;
public long SuccessPing = 0;
public long FailPing = 0;
public DateTime LastSuccessPing;
public override string ToString() {
return $"Sping: {SuccessPing} last={LastSuccessPing}, Fping:{FailPing}, reply:{reply}";
}
}
public class OneAddressPing {
public static byte[] bu = {
0
};
public long _FailReply;
public long _SuccessReply;
private bool bStop = false;
private readonly CancellationToken cancellationToken;
public DateTime LastSuccessfullPing = DateTime.MinValue;
public int mSecBetweenPing = 3000;
public Ping ping;
public PingOptions popt;
private Task pTask;
// Here is a self-written LIFO stack
public LightQueue<PingReply> replys = new LightQueue<PingReply>(10);
private readonly AutoResetEvent reset = new AutoResetEvent(false);
private Logger log = null;
private Task pinging = null;
public OneAddressPing(IPAddress addr, CancellationToken ct, int timeOut = 3000, int BetweenPing = 3000, Logger _log =null) {
ipAddress = addr;
popt = new PingOptions();
popt.DontFragment = false;
cancellationToken = ct;
mSecTimeOut = timeOut;
mSecBetweenPing = BetweenPing;
log = _log;
}
public int mSecTimeOut { get; set; } = 3000;
public IPAddress ipAddress { get; set; }
public int CountPings => replys.Length;
private void SetReply(PingReply rep) {
if (rep == null) return;
replys.Put(rep);
if (rep.Status == IPStatus.Success) {
Interlocked.Increment(ref _SuccessReply);
LastSuccessfullPing = DateTime.Now;
} else {
Interlocked.Increment(ref _FailReply);
}
}
public async Task Start() {
if (pTask == null || pTask.Status != TaskStatus.Running) {
ping = new Ping();
Task.Factory.StartNew(PingCircle, TaskCreationOptions.RunContinuationsAsynchronously | TaskCreationOptions.LongRunning); pTask = Task.Run(PingCircle, cancellationToken);
}
}
public void Stop() {
if (pTask.Status == TaskStatus.Running) {
bStop = true;
try {
pTask.Wait(mSecTimeOut, cancellationToken);
} catch (Exception ex) {
log.ErrorSource($"Error ping stop: {ex.Message}");
}
}
}
private async Task PingCircle() {
while (cancellationToken.IsCancellationRequested == false && !bStop) {
try {
try {
PingReply rep = await ping.SendPingAsync(ipAddress, mSecTimeOut, bu,popt);
if (rep != null) SetReply(rep);
} catch (PingException p) {
// ignore ping error
Debug.WriteLine($"error: {p}");
} catch (Exception ee) {
log?.ErrorSource(ee);
Debug.WriteLine($"error: {ee}");
}
await Task.Delay(mSecBetweenPing, cancellationToken);
} catch (Exception ee) {
log?.ErrorSource(ee);
}
}
}
public PingReply GetReply() {
if (replys.IsEmpty) return null;
return replys.PeekLast(0);
}
public Tuple<long, long> GetSuccessOperation() {
return new Tuple<long, long>(_SuccessReply, _FailReply);
}
public bool LongPingSuccess() {
int ret = 0;
for (int i = 0; i < 5; i++) {
var r = replys.PeekLast(i);
if (r.Status == IPStatus.Success) ret++;
}
if (ret > 2) return true;
return false;
}
}

Categories

Resources