How To Exit or End a C Sharp (C#) Application
12-06-2012 To exit a c# program simply use following command: Environment.Exit(int Status); Status is the integer you return to tell the environment how your program concludes. If it executed according as expected or if it encountered any errors. ...

The Dashed Print Area Line in Excel
01-06-2012 Excel shows which content will be included in a page (when printed) with a dashed outline. If you can't see this follow these steps (just one of them 🙂 ): Go to File Menu and Select Print You don't have to do a print or anything just...


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

Replace Function Doesn't Replace Double Quotation in VBA
13-11-2012 I had to remove all double quotation marks from a string using VBA. I tried to do this by using the Replace function as shown below. Also Note that two double quotation marks are used to represent the quotation mark. This is because the...

ILT - Simple technique to toggle between true and false or one and zero
20/06/2013 If you want to toggle a value from 1 to 0 or 0 to 1 depending on the current value then you are at the right place. (i.e. change the value to 0 only if it's 1 now and change it to 1 only if it is 0 at the moment) You can use this to togg...

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