c#


Async Operation In Destructor


Trying to run async operation in class destructor is fail.
This is the code:
public class Executor
{
public static void Main()
{
var c1 = new Class1();
c1.DoSomething();
}
}
public class Class1
{
public void DoSomething()
{
}
private int _i = 100;
private int _j = 100;
~Class1()
{
Task.Run(() => _j *= 2); //Does not progress _j
_i *= 2; //Progress _i from 100 to 200
Thread.Sleep(1000);
Console.WriteLine("In destructor. _i = " + _i);
Console.WriteLine("In destructor. _j = " + _j);
}
}
And the output is:
In destructor. _i = 200
In destructor. _j = 100
Following Destructor page on MSDN does not mention threads/async aspects of instance destruction.
So any ideas?
Thank you
In your particular example new thread cannot be started because runtime is terminating and app domain is unloading. When app domain unloads - it will run all finalizers and shutdown all threads. You can verify this with:
Console.WriteLine("shutdown:" + Environment.HasShutdownStarted);
Which will return true in your case. If you modify you example like this:
class Program {
static void Main(string[] args) {
var c1 = new Class1();
c1.DoSomething();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.ReadKey();
}
}
public class Class1
{
public void DoSomething()
{
}
private volatile int _i = 100;
private volatile int _j = 100;
~Class1()
{
Console.WriteLine("shutdown:" + Environment.HasShutdownStarted);
Task.Run(() => _j *= 2); //Does not progress _j
//_i *= 2; //Progress _i from 100 to 200
Thread.Sleep(1000);
Console.WriteLine("In destructor. _i = " + _i);
Console.WriteLine("In destructor. _j = " + _j);
}
}
And compile in Release mode with optimizations - you will see that now runtime is not terminating and your task will run fine.
Obviously you should never do such things in finalizer, but just so that you know the real reason.

Related Links

ImageResizer: Disable size limitation of resizing
Multiple Select for Edit User Wtih CheckBox
Action Not Firing When Button Clicked
Catch and change keyboard on mac sierra to emulate neo2 keyboard layout
Deserializing JSON using C# to return items
How to make a triangular location in C#?
What is the option in C# having capability of same like 'IN' in SQl
How to configure Visual Studio to not indent closing parenthesis on multiline function calls?
C# Interface base usage
Creating a named .txt file and subsequently writing string to it in C#
How to create file compare and copy program? [closed]
.NET Core IConfigurationRoot with UserSecrets outside of main method
Composable CustomControl that supports Attribute and Object Notation Binding
SQL expressions as column name with Oracle 12c database
Check if an user is member of some Azure Active Directory Tenant
Translate nested anonymous functions to foreach loop

Categories

HOME
reactjs
gulp
botframework
virtual-machine
fortran
process
itext7
bitbucket
esxi
mailchimp
sugarcrm
kohana
meson-build
virtualhost
apache-httpclient-4.x
mongoimport
velocity
camunda
opengrok
swift3.1
popup
taxonomy
ringcentral
ofbiz
project-reactor
legend-properties
ampscript
descriptor
git-branch
connectiq
policy
sha
core-animation
suitescript
inspec
hierarchical-data
sphinx4
ibm-bpm
ng2-bootstrap
webmock
android-geofence
cache-control
ponylang
device-driver
matrix-multiplication
area
ng-lightning
office-interop
electron-packager
jvisualvm
intervention
smooth-streaming
html-entities
taleo
monaca
riemann
visualizer
px4
activesupport
grib
bipartite
msiexec
nls
spring-social-twitter
glade
consolidation
symantec
eclipse-mars
dbi
universe
netlink
qtruby
transaction-isolation
treelist
wizard
hana-sql-script
page-flipping
litedb
eggplant
android-networking
page-refresh
autopep8
crystal-reports-7
grunt-contrib-connect
conditional-comments
go-gin
time-frequency
step
mvcgrid
fastcgi-mono-server
pthreads-win32
db2-connect
logo-lang
octokit
kademlia
cloudmade
auctex
microsoft-speech-platform
ncml
derived-class
sup
nsscrollview
datejs
umfpack
cryptolicensing
pitch-shifting
code-golf
morfik
expander
cross-cutting-concerns

Resources

Encrypt Message