quote
If you sell for a high price, people will think before they buy and if you sell for a low price then they will wonder. - Cassian Menol Razeek

Comparing Objects in .Net - Reference Equality
30-05-2012 Comparing two objects returns true if they point to the same entry of the heap. Public Class Person { Private String Name; Private int Age; Public Person(String Name) { this.Name = Name; ...

Web development resources


Adding or Subtracting a Date Time Variable in SQL Server Using DateAdd Function
28-05-2012 You can use dateadd function to add or subtract a number of units from any part (year, month, day, hour, minute, second, millisecond, etc...) of a datetime variable. Syntax: - DateAdd(Date Part, Number Of Units To Add, Source Date) Date...


Growth of personality is often mistaken as loss of humanity. - 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