a.toraby
a.toraby

Reputation: 3391

Why invoking the event cancels the task?

I have a Task that checks the time of a device per second:

public void checkTimeStart()
{
  CancellationTokenSource cTokenSource = new CancellationTokenSource();
  CancellationToken ct = cTokenSource.Token;
  Task task = Task.Factory.StartNew(async () =>
    {
      ct.ThrowIfCancellationRequested();
      while (!ct.IsCancellationRequested)
         {
           await Task.Delay(1000);
           string time = getTime();
           TimeUpdateEvent.Invoke(this, new TimeUpdateEventArgs(time));
          }
     }, cTokenSource.Token);
}

This works perfect if I remove the TimeUpdateEvent.Invoke(this, new TimeUpdateEventArgs(time));. But when I try to invoke the event the task stops completely and it never enters the while loop! I need this event to update time text box whenever I recieve the new time from the device.


I know its possible to update ui directly from anonymous task but this method is implemented in a portable class library. I need it to be platform independent. So every user could update its own ui when they receive TimeUpdateEvent. TimeUpdateEvent is a simple custom event.

Upvotes: 0

Views: 66

Answers (1)

konak
konak

Reputation: 129

Please check if there is any subscription to the event "TimeUpdateEvent" before calling the "checkTimeStart()" method. I think you didn't make any subscription, so on invoking that event system halts. If you will put the invocation part of the code in try catch block:

try
{
    TimeUpdateEvent.Invoke(this, new TimeUpdateEventArgs(time));
}
catch (Exception ex)
{
    throw;
}

you will get a NullReferenceException .... So please check the subscription to that event.

Wish you all the best !

Upvotes: 2

Related Questions