c# - Should I declare variables accesed by a SerialPort's callback as synchronized? -


i have callback added datareceived event of serialport. callback accesses class' properties. so, must these properties declared synchronized? in other words, possible main thread accesses property while callback writing on it?

here put example:

class {     private serialport serialport;      [methodimpl(methodimploptions.synchronized)] // <-- necessary?     public int prop { get; set; }      public a(serialport sp){         serialport = sp;         serialport.datareceived += (object sender, serialdatareceivedeventargs e) => {             prop++;         };     }  } 

that's possible don't know whether happens because code of main thread not visible here.

if 2 threads access prop must synchronized in form. in demo code [methodimpl(methodimploptions.synchronized)] enough. want protect more state single value. in case need lock manually using lock.

[methodimpl(methodimploptions.synchronized)] code smell anyway. believe it's there java compatibility. 15 years ago microsoft thought people might want migrate java .net lot.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -