5 Ways to Get Rid of Financial Stress and Optimal Utilization of Money
2008-12-14 With the rise of Global Financial Crisis, Financial stress has become a hot topic in the Internet. Since I am also a victim, I thought to make a small research on this. In this post I am trying my best to explain what I gained during m...

html css it is not possible to have inline styles for different aspects of an element like hover, and visited
You cannot specify css styles for different aspects of an HTML element. e.g. I wanted to do something like this. But you CAN NOT do this. <a href="www.unicef.org" style="hover(color:00AEFD);active(co...

quote
If you care about others without thinking about yourself, then God will care about you. - Cassian Menol Razeek

Stop asp.net from encoding the source HTML string (mvc raw html)
/// Stops asp.net from encoding the source HTML string. public static IHtmlString HTMLRaw(string source) { return new HtmlString(source); } call this function whenever you want asp.net NOT to encode the string. Note: You can use <%= and %> t...

Books I have read since the beginning of 2016
These are the books I have read (or listened to their audio counterparts) since the beginning of 2016. I am not going to write my opinion about each of these books, instead I hope you too trust the majority of the people from around the world wh...

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