Calling an event handler from within an async block in C# crashes application

Answered Calling an event handler from within an async block in C# crashes application

  • 11 марта 2012 г. 4:28
     
      С кодом

    When trying to write an application that uses a small C# project (to process byte buffers and utf conversions), the application crashes if I try to call the event handler from within an async block. Code as simple as this can trigger the behavior:

    using System;
    using System.Threading.Tasks;
    using Windows.Foundation;
    
    namespace DotNet
    {
        public sealed class DotNetEvents
        {
            public event EventHandler<string> Stuff;
    
            public IAsyncOperation<string> DoStuff()
            {
                if (Stuff != null) Stuff(this, "Does not crash");
    
                return Task.Run<string>(async () =>
                {
                    if (Stuff != null) Stuff(this, "Crashes");
    
                    return "true";
                }).AsAsyncOperation<string>();
            }
        }
    }
    

    And the JS code:

    var ev = new DotNet.DotNetEvents();
    ev.addEventListener("stuff", function (s) {
        console.log(s);
    });
    ev.doStuff().then(function (x) {
        console.log(x);
    });

    Luis

Все ответы

  • 11 марта 2012 г. 4:36
     
      С кодом

    The exception thrown is the following:

    A first chance exception of type 'System.InvalidCastException' occurred in DotNet.winmd
    
    Additional information: Unable to cast COM object of type 'System.EventHandler`1[System.String]' to class type 'System.EventHandler`1[System.String]'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.



    LHC

  • 12 марта 2012 г. 14:00
    Модератор
     
     
  • 12 марта 2012 г. 16:24
     
     

    Hi Jeff!

    Async methods work perfectly fine (in fact, in the example I'm using, if you comment the line with the "Crashes", it mostly boils down to the example you sent. That part works as expected. Also, AsyncInfoFactory does not exist anymore in the Consumer Preview). The trouble comes when trying to raise an event from within that async method (which I need to signal various other objects to do something).

    Luis


    LHC

  • 16 марта 2012 г. 19:28
    Модератор
     
     
    Taking offline via email...  Will update forum at a later date.

    Jeff Sanders (MSFT)

  • 26 апреля 2012 г. 18:17
     
     

    Hi Jeff,

    Is there a workaround or solution to this?  I am experiencing the same problem and could not figure it out.

    Thanks