c# - CancellationTokenSource, When to dispose? -


this question has answer here:

when supposed dispose of cancellationtokensource? if example make 1 , put in threads everytime click button:

    private void button_click(object sender, eventargs e)     {         if (clicked == false)         {              clicked = true;             ctssend = new cancellationtokensource();             thread1 = new thread(() => method1(ctssend.token));              thread1.start();             thread2 = new thread(() => method2(ctssend.token));              thread2.start();         }         else         {             ctssend.cancel();             ctssend.dispose();             clicked = false;         }     } 

am supposed dispose of that? cause if so, bit problematic need put in disposer dispose when application closes, there isn´t guarantee won´t disposed if not waiting it, , cause objectdisposedexception.

i tried prevent exception (as not use try catch, not error in first place in case).

        if (ctssend != null)         {             ctssend.cancel();             ctssend.dispose();         }         if (ctsreceive != null)         {             ctsreceive.cancel();             ctsreceive.dispose();         } 

but well, maybe should dispose of in end, , don´t dispose of after cancel everytime? though don´t how keep adding resources new object.

how people these cases?

edit:

a more concrete question solve (in case).

how can bound bool cancellationtoken? can have cts.isdisposed;

some objects have that, cts doesn´t, if had, solve problem having. using bool separately, isn´t prefer.

they did analysis here when dispose cancellationtokensource? , seems it's quite useless try correctly dispose it. let gc collect (and if in examples of msdn isn't disposed)


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -