c语言线程不安全错误定位,C语言中的线程安全可破坏事件触发类#
最近,我被要求實現一個類作為選擇過程的一部分。我按要求做了這個節目。但是,我考試不及格。我真的很想知道我的解決方案出了什么問題。任何幫助都非常感謝。問題和我的解決方案如下
實現一個線程安全類,該類在構造過程中每秒觸發一個事件。需要有一個函數來查找經過的秒數。這個類必須實現IDisposable,調用dispose后對seconds elapsed函數的任何調用都應該失敗。
我的解決方案:
namespace TimeCounter
{
public delegate void SecondsElapsedHandler(object o, EventArgs e);
///
/// Summary description for SecondCounter
///
public class SecondCounter : IDisposable
{
private volatile int nSecondsElapsed;
Timer myTimer;
private readonly object EventLock = new object();
private SecondsElapsedHandler secondsHandler;
public SecondCounter()
{
nSecondsElapsed = 0;
myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler(OneSecondElapsed);
myTimer.Interval = 1000;
myTimer.AutoReset = false;
myTimer.Start();
}
public void OneSecondElapsed(object source, ElapsedEventArgs e)
{
try
{
SecondsElapsedHandler handlerCopy;
lock (EventLock)
{
handlerCopy = secondsHandler;
nSecondsElapsed++;
}
if (secondsHandler != null)
{
secondsHandler(this, e);
}
}
catch (Exception exp)
{
Console.WriteLine("Exception thrown from SecondCounter OneSecondElapsed " + exp.Message);
}
finally
{
if (myTimer != null)
{
myTimer.Enabled = true;
}
}
}
public event SecondsElapsedHandler AnotherSecondElapsed
{
add
{
lock (EventLock)
{
secondsHandler += value;
}
}
remove
{
lock (EventLock)
{
secondsHandler -= value;
}
}
}
public int SecondsElapsed()
{
if (this.IsDisposed)
{
throw new ObjectDisposedException("SecondCounter");
}
return nSecondsElapsed;
}
private bool IsDisposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool Disposing)
{
if (!IsDisposed)
{
if (Disposing)
{
}
if (myTimer != null)
{
myTimer.Dispose();
}
}
secondsHandler = null;
IsDisposed = true;
}
~SecondCounter()
{
Dispose(false);
}
}
}
總結
以上是生活随笔為你收集整理的c语言线程不安全错误定位,C语言中的线程安全可破坏事件触发类#的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css鼠标变成小手_技巧篇:CSS高级技
- 下一篇: 【LeetCode笔记】1143. 最长