I absolutely understand your requirements, but you missed one important thing: do you really need to wait for this thread to finish synchronously? Or maybe you just need to execute the “finalizer” after detecting the end of the stream?
In the latter case, just wrap the call to myLongRunningTask in another method:
void surrogateThreadRoutine() { // try{ .. mytask(); // finally { .. ..all 'finalization'.. or ie raising some Event that you'll handle elsewhere }
and use it as a thread routine. Thus, you will find out that finalization will occur in the stream and immediately after the end of the actual task.
However, of course, if you work with some user interfaces or other schedulers, now the “finalization” will work on your thread , and not on the “normal threads” of your interface or comm., You will need to make sure that all resources are external in relation to your streaming task, correctly protected or synchronized, otherwise you are likely to come across other application streams.
For example, in WinForms, before you touch any user interface elements from the finalizer, you will need Control.InvokeRequired (surely = true) and Control.BeginInvoke / Invoke to return the context back to the user interface stream.
For example, in WPF, before touching any user interface elements from the finalizer, you will need Dispatcher.BeginInvoke ..
Or, if a collision can occur with any threads you control, a simple lock() enough. and etc.
quetzalcoatl
source share