簡體   English   中英

是否可以在c#中為靜態對象賦值新的線程安全

[英]is it thread safe to assign a new value to a static object in c#

采用以下代碼,在多線程環境中會發生什么:

static Dictionary<string,string> _events = new Dictionary<string,string>();

public static Dictionary<string,string> Events { get { return _events;} }

public static void ResetDictionary()
{
    _events = new Dictionary<string,string>();
}

在多線程環境中,可以通過不同的線程同時訪問此方法和屬性。

將新對象分配給可在不同線程中訪問的靜態變量是否安全? 什么可能出錯?

有什么時候事件可以為空嗎? 如果2個線程同時調用EventsResetDictionary()

將新對象分配給可在不同線程中訪問的靜態變量是否安全?

基本上,是的。 從某種意義上說,該屬性永遠不會無效或為null

什么可能出錯?

另一個線程重置后,讀取線程可以繼續使用舊字典。 這有多糟糕取決於您的程序邏輯和要求。

如果你想控制多線程環境中的所有內容,你必須使用所有踏板都可以訪問的標志,並控制你在字典上使用的方法!

// the dictionary
static Dictionary<string, string> _events = new Dictionary<string, string>();

// public boolean
static bool isIdle = true;

// metod that a thread calls
bool doSomthingToDictionary()
{
    // if another thread is using this method do nothing,
    // just return false. (the thread will get false and try another time!)
    if (!isIdle) return false;

    // if it is Idle then:
    isIdle = false;
    ResetDictionary(); // do anything to your dictionary here
    isIdle = true;
    return true;
}

另一件事! 您可以使用Invoke方法確保當一個線程正在操作變量或在另一個線程中調用函數時,其他線程將不會! 請參閱鏈接: 調用跨線程事件的最簡潔方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM