[英]Custom events in C# specifically is the sender object thread safe
好的,所以我正在實現一組自定義事件。 首先,它們將與多線程環境一起使用,以在整個線程中傳達主要成就。 現在,我現在有一個簡單的設置:
public delegate void TestEventHandler(object sender, TestEventArgs e);
public class Test
{
bool _stopTesting = false;
int _runs = 0;
public event TestEventHandler Tester;
protected virtual void OnTest(TestEventArgs e)
{
TestEventHandler hand = Tester;
if (hand != null)
hand(this, e);
}
public void StartTest()
{
while (!_stopTesting)
{
_runs++;
TestEventArgs e = new TestEventArgs(true, 100000);
OnTest(e);
}
}
}
public class TestMe
{
public void TestMeHard(object sender, TestEventArgs e)
{
Test check = sender as Test;
Console.WriteLine(e.Message);
}
}
事件args類在其他地方定義。 我的問題是, sender
對象線程是否安全,並且原諒這個笨拙的問題,但是sender
對象是引用還是副本? 就像在觸發事件的實際對象中一樣,對發送方對象的任何更改都將被反映出來嗎?
發件人對象是參考,而不是副本。
現在到線程安全問題,它取決於在sender參數中傳遞的對象。 由於發送方對象是一般類型的,因此需要將其轉換為適當的類型才能使用它。 它可以表示任何對象,很難說它是否安全。
通過這篇文章了解如何編寫線程安全類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.