System.Timers.Timer совсем не ясно, как работать - C#
Формулировка задачи:
Вообщем я прочитал кучу статей, возможно не очень внимательно.
Вообщем как я понимаю у System.Timers.Timer каждый тик выполняется в отдельном потоке, причем не дожидаясь конца предыдущего тика. У меня через данный таймер реализована запись в файл. Интервал 200мс. Иногда возникают случаи, когда запись не успевает выполнится за 200мс, в таких ситуациях следующий тик не может обратиться к файлу, так как он занят.
Как поступить в данной ситуации подскажите?
Решение задачи: «System.Timers.Timer совсем не ясно, как работать»
textual
Листинг программы
- using System;
- using System.Collections.Concurrent;
- using System.IO;
- using System.Threading;
- using System.Threading.Tasks;
- namespace timurchak
- {
- class Logger
- {
- private Task mTask;
- private CancellationTokenSource mToken;
- private string mFileName;
- private ConcurrentQueue<string> mQueue;
- private ManualResetEventSlim mNewEvent;
- public Logger()
- {
- this.mTask = null;
- this.mToken = null;
- this.mFileName = null;
- this.mQueue = new ConcurrentQueue<string>();
- this.mNewEvent = new ManualResetEventSlim(false);
- }
- public void Start(string filename)
- {
- this.mFileName = filename;
- this.Stop();
- this.mToken = new CancellationTokenSource();
- this.mTask = Task.Factory.StartNew(o => this.Process((CancellationToken)o), this.mToken.Token, this.mToken.Token);
- }
- public void Stop()
- {
- if (this.mTask != null)
- {
- try
- {
- this.mToken.Cancel();
- this.mTask.Wait();
- }
- catch (AggregateException)
- {
- }
- finally
- {
- this.mTask = null;
- this.mToken = null;
- }
- }
- }
- private void Process(CancellationToken token)
- {
- while (true)
- {
- token.ThrowIfCancellationRequested();
- this.mNewEvent.Wait(token);
- if (this.mQueue.Count > 0)
- {
- this.mNewEvent.Reset();
- using (StreamWriter writer = new StreamWriter(this.mFileName, true))
- {
- string message;
- while (this.mQueue.TryDequeue(out message))
- {
- writer.WriteLine(message);
- }
- }
- }
- }
- }
- public void PutMessage(string message)
- {
- this.mQueue.Enqueue(message);
- this.mNewEvent.Set();
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д