日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

c语言线程不安全错误定位,C语言中的线程安全可破坏事件触发类#

發布時間:2024/7/23 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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语言中的线程安全可破坏事件触发类#的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。