Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with Async method #2

Open
PetroProtsyk opened this issue Jan 12, 2011 · 0 comments
Open

Problem with Async method #2

PetroProtsyk opened this issue Jan 12, 2011 · 0 comments

Comments

@PetroProtsyk
Copy link
Owner

While using RunCode in combination of Event handlers being invoked from background thread side effects are possible. In the example below exception will appear because context will be clear immediately after call to RunCode, but will be still referenced and used by the event handler which will be invoked afterwards as a result of async function execution:

[TestMethod]
public void ProblemWithGlobalScopeWithAsyncEvents() {
    CustomerFacade rez = (CustomerFacade)Script.RunCode(@"
        abc = '123';
        function OnGetCustomersCompleted(s, e)
        {
            s.v = abc;
        }

        s = new CustomerFacade();
        s.GetCustomersCompleted += OnGetCustomersCompleted;
        s.GetCustomersAsync();

        return s;
     ");

    //Now scope is clear, while event is still subscribed and will be invoked
    while (rez.busy) System.Threading.Thread.Sleep(100);
    Assert.IsTrue(rez.v.Contains("given handler is not associated with any context"));
}

public class CustomerFacade {

  public event EventHandler<EventArgs> GetCustomersCompleted;

  public string v { get; set; }

  public bool busy { get; set; }

  public void GetCustomersAsync()
  {
      busy = true;

      Task t = Task.Factory.StartNew(
          () => {
              System.Threading.Thread.Sleep(500);

              try {
                  if (GetCustomersCompleted != null) {
                      GetCustomersCompleted.Invoke(this, EventArgs.Empty);
                  }
              }
              catch(Exception e)
              {
                  v = e.ToString();
              }
              finally {
                  busy = false;
              }
          });
  }

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant