If you’re blessed with a fast brain, use it happily but don’t expect others to work at your speed nor criticize them even inside your mind - Cassian Menol Razeek

How to force your website to download a file (rather than opening)
07/05/2013 I wanted to add a download link to one of my products. The file was an Windows Installer Package (*.msi). However, FireFox started to open the file on the browser rather than downloading it so when my visitors tried to download the insta...

When (or not) to Hyphenate Compound Adjectives
2016-07-06 Use hyphen only when the compound adjective comes before the noun. e.g. 1 - The candidate provided an up-to-date curriculum vitae. 2 - The curriculum vitae provided by the candidate was not up to date. References: dailywrit...

About
I am Cassian Menol Razeek. I am presently working as a software engineer and at the moment I am in the pursuit of excellence for both my carrier and personal life. I live in beautiful Sri Lanka, "The Pearl of the Indian Ocean" If you like to conta...

ILT: [Solved] Nexus 5 Randomly Restarting After Upgrading to Marshmallow
One night I allowed my Nexus 5 to upgrade to the latest Android version (Marshmallow) but from next morning my phone was behaving very strangely. It kept restarting randomly and became almost useless and completely unreliable.   The Pro...

Posted in General | Comments Off on

Solved: The destination thread no longer exists exception – C#

2016-11-08

You will get System.ComponentModel.InvalidAsynchronousStateException (The destination thread no longer exists.) if a UI component gets disposed or the UI thread EXITs while a different thread is in the middle of invoking a change on the same UI component.

This usually happens when a user closes a window (form) that has been updated by a different thread.

You can make the form to gracefully close itself after waiting for existing invokes by following steps.

1 – Intercept the thread exiting code (e.g. form closing event can be used to intercept a form close)
2 – Advice any methods that creates invokes to stop creating any new invokes (can be achieved by setting a flag e.g. stopInvoking flag in the example)
3 – Wait for any existing invokes to finish (set another flag before each invoke and reset it after invoke finishes and use it to determine if an invoke is in progress e.g. invokeInProgress flag in example)

As seen in the example, you may make the stopInvoking flag public so any clients that try to use the Form may know that you are no longer in business so they also get to handle the situation gracefully.

flags

private bool invokeInProgress = false;
private bool stopInvoking = false
public bool ShuttingDown { get { return stopInvoking; } }

invoking code

        public void AddItem(string newItem)
        {

            if (listView1.InvokeRequired)
            {
                if (stopInvoking != true) // don't start new invokes if the flag is set
                {
                    invokeInProgress = true;  // let the form know if an invoke has started

                    listView1.Invoke(new Action(() => addItem(newItem)));

                    invokeInProgress = false;  // the invoke is complete
                }

                return;
            }

            listView1.Items.Add(newItem);
            listView1.Items[listView1.Items.Count - 1].EnsureVisible();
        }

intercepting and managing form closing event

        private async void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (invokeInProgress)
            {
                e.Cancel = true;  // cancel the original event 

                stopInvoking = true; // advise to stop taking new work

                // now wait until current invoke finishes
                await Task.Factory.StartNew(() =>
                                {
                                    while (invokeInProgress);  
                                });

                // now close the form
                this.Close();
            }
        }

example client code that can recognise the problem and handle accordingly

        static void Main()
        {
            Form1 frm = new Form1();

            Task.Factory.StartNew(() => frm.ShowDialog(), TaskCreationOptions.LongRunning);

            int i = 0;
            while (i < 2000)
            {
                if (frm.ShuttingDown != true)  // the clients can also be notified and allowed to handle the UI disruption
                {
                    frm.AddItem(Guid.NewGuid().ToString());
                }
                else
                {
                    MessageBox.Show("Form is closing. Stopping the process.");
                    break;
                }

                i++;
            }

            MessageBox.Show("Program completed! i=" + i.ToString());
        }

Download source code (VS 2013 solution)
background-thread-already-closed

Posted in C#.Net, Microsoft .Net Framework | Tagged , , , , | Leave a comment

Using multiple versions of Entity Framework in the same solution

2016/07/20

Using multiple versions of Entity framework by different projects within the same solution.

I had to develop a pilot project to use Entity framework (EF) 6.0 inside the solution that already has other projects that refers to EF 4.4.

While debugging I received this error:

Could not load file or assembly ‘EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

entity framework error b77a5c561934e089

entity framework error b77a5c561934e089

 

 

 

 

 

 

This can be solved by adding following configuration to the web.config file.



<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
     <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.4.0.0" newVersion="4.4.0.0" />
        <codeBase version="4.4.0.0" href="bin\ef44\EntityFramework.dll"/>
     </dependentAssembly>
     <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
        <bindingRedirect oldVersion="4.4.0.0-6.0.0.0" newVersion="6.0.0.0" />
     </dependentAssembly>
      
   </assemblyBinding>
</runtime>

The Dependent Assembly entries inform the Run Time to use version for 4.4.0.0 for any project that require a version between 0.0.0.0 to 4.4.0.0 and use the version 6.0.0.0 for any project that require EF between 4.4.0.0 to 6.0.0.0.

The code base entry under the first dependent assembly advises the run time to locate  the  4.4.0.0 version of entity framework (EntityFramework.dll) under bin\ef44 folder.

The other version of EntityFramework.dll will be located in the usual bin folder.

Note: this article explains how you can find the publicKeyToken for any dll file or assembly.

References:

Posted in C#.Net | Tagged , , , , | Leave a comment