Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 140357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T07:36:01+00:00 2026-05-11T07:36:01+00:00

I can’t seem to figure out why I am getting an InvalidCastException running the

  • 0

I can’t seem to figure out why I am getting an InvalidCastException running the following code:

var item = new KeyValuePair<string, string>('key', 'value');  Action<KeyValuePair<string, string>> kvrAction =      kvr =>Console.WriteLine(kvr.Value);  var result = kvrAction.BeginInvoke(item, null, null); kvrAction.EndInvoke(result); 

Exception Info:

Test method Utilities.Tests.IEnumerableExtensionTests.ProveDelegateAsyncInvokeFailsForKeyValuePair threw exception:  System.Runtime.Remoting.RemotingException: The argument type '[key, value]' cannot be converted into parameter type 'System.Collections.Generic.KeyValuePair`2[System.String,System.String]'. --->  System.InvalidCastException: Object must implement IConvertible.. 

Any assistance would be appreciated =) This code seems to work with anything I throw at it except a KeyValuePair<>.

Update: It appears this condition exists for any struct. I hadn’t noticed KeyValuePair<> was a struct and so was only testing with classes. I still don’t understand why this is the case though.

Update 2: Simon’s answer helped confirm this behavior is unexpected, however implementing a custom type won’t work for what I’m trying to do. I am trying to implement an extension method on IEnumerable<> to execute a delegate Asynchronously for each item. I noticed the error running tests against a generic Dictionary object.

    public static IEnumerable<T> ForEachAsync<T>(this IEnumerable<T> input, Action<T> act)     {         foreach (var item in input)         {             act.BeginInvoke(item, new AsyncCallback(EndAsyncCall<T>), null);         }          return input;     }      private static void EndAsyncCall<T>(IAsyncResult result)     {         AsyncResult r = (AsyncResult)result;         if (!r.EndInvokeCalled)         {             var d = (Action<T>)((r).AsyncDelegate);             d.EndInvoke(result);         }     } 

I would rather not limit the method with a constraint on T to ensure only classes are used so I have refactored the method as follows to get around the problem with BeginInvoke but I have not worked with the TreadPool directly before and would like to make sure I am not missing anything important.

    public static IEnumerable<T> ForEachAsync<T>(this IEnumerable<T> input, Action<T> act)     {         foreach (var item in input)             ThreadPool.QueueUserWorkItem(obj => act((T)obj), item);          return input;     } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T07:36:01+00:00Added an answer on May 11, 2026 at 7:36 am

    Odd, seems to be some sort of bug in .NET (C#?) with marshalling the argument to the worker thread.

    If you implement IConvertable on the passed struct:

    struct MyPair<TKey, TValue> : IConvertable {     public readonly TKey Key;     public readonly TValue Value;      public MyPair(TKey key, TValue value)     {         Key = key;         Value = value;     }      // I just used the smart-tag on IConvertable to get all these...     // public X ToX(IFormatProvider provider) { throw new InvalidCastException(); }      ...      public object ToType(Type conversionType, IFormatProvider provider)     {         if (typeof(MyPair<TKey, TValue>).GUID == conversionType.GUID)             return this;         throw new InvalidCastException();     } } 

    It runs fine. The passed conversionType doesnt pass .Equal(), IsAssignableFrom(), or anything else I tried except GUID comparison, which is probably related to why it asks for an IConvertable in the first place.

    EDIT: A simple workaround is to use closures to pass the parameter:

    var data = new Dictionary<string, string> {     { 'Hello', 'World' },     { 'How are', 'You?' },     { 'Goodbye', 'World!' } }; foreach (var pair in data) {     var copy = pair; // define a different variable for each worker     Action worker = () => Console.WriteLine('Item {0}, {1}', copy.Key, copy.Value);     worker.BeginInvoke(null, null); } 

    Of course, if you need the results, you will need to store the IAsyncResults, which will probably have the same issue as parameters, in the other direction. As an alternative, you could add them to a collection when they are complete, but the locking gets a bit weird:

    var data = new Dictionary<string, string> {     { 'Hello', 'World' },     { 'How are', 'You?' },     { 'Goodbye', 'World!' } };  var results = new List<KeyValuePair<string, string>>(); var pending = 0; var done = new ManualResetEvent(false);  var workers = new List<Action>(); foreach (var pair in data) {     ++pending;     var copy = pair; // define a different variable for each worker     workers.Add(delegate()     {         Console.WriteLine('Item {0}, {1}', copy.Key, copy.Value);         lock (results)             results.Add(new KeyValuePair<string, string>('New ' + copy.Key, 'New ' + copy.Value));         if (0 == Interlocked.Decrement(ref pending))             done.Set();     }); }  foreach (var worker in workers)     worker.BeginInvoke(null, null);  done.WaitOne();  foreach (var pair in results)     Console.WriteLine('Result {0}, {1}', pair.Key, pair.Value); 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can someone please help me figure out why my accordion script at http://www.mincovlaw.com/services/copyright gets
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Can anybody tell what is the best(easy) way to sort the following string 'index'
Can't figure out how to do this in a pretty way : I have
can any one tell me how can change this java code into objective c.is
Can the Application Name passed to SQL Server (via the ADO Connection string) be
Can we do following in SQL Server 2005 query with convert function. MaxRegID =
Can anyone give me an example of how to return the following json simply
can someone explain why the compiler accepts only this code template<typename L, size_t offset,
Can't work out a way to make an array of buttons in android. This

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.