ILT - Divide and Conquer Strategy - Why it is so powerful
08/02/2013 Divide and Conquer is a very interesting and effective strategy that has been used by many technical experts, leaders, mangers, and warriors through out the world for many years. Following is a story of the famous Sri Lankan king Dutugem...

Preserving milliseconds when passing dates around front end
2016-06-08 Instead of passing the datetime pass the datetime.Ticks which is a (long) numeric value so the complete datetime value will be preserved. Then convert ticks back to datetime in the server (controller \ action method). [sourcecode ...

What is Go in SQL Server and the Importance of Using Go
25-05-2012 Go is not a SQL or Transact SQL command. Go is a command recognized by sqlcmd and osql facilities provided by SQL server studio. Go specifies an end to a particular SQL batch. Once the parser interprets a Go, that block is considered com...

Browser and length independent CSV download code
17-09-2015 Downloading a csv string as a file on browser can be troublesome. Some techniques don't work for very long CSV strings and some techniques only work on some browsers. Below code is tested on Internet Explorer 11, Firefox 27.0.1, and ...


When you try to win everything you tend to lose more things because you have blinded your mind -Cassian Menol Razeek

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