Raising events on separate thread

前端 未结 5 1677
耶瑟儿~
耶瑟儿~ 2020-12-29 06:07

I am developing a component which needs to process the live feed and broadcast the data to the listeners in pretty fast manner ( with about 100 nano second level accuracy, e

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 06:41

    You can use these simple extension methods on your event handlers:

    public static void Raise(this EventHandler handler, object sender, T e) where T : EventArgs {
        if (handler != null) handler(sender, e);
    }
    
    public static void Raise(this EventHandler handler, object sender, EventArgs e) {
        if (handler != null) handler(sender, e);
    }
    
    public static void RaiseOnDifferentThread(this EventHandler handler, object sender, T e) where T : EventArgs {
        if (handler != null) Task.Factory.StartNewOnDifferentThread(() => handler.Raise(sender, e));
    }
    
    public static void RaiseOnDifferentThread(this EventHandler handler, object sender, EventArgs e) {
        if (handler != null) Task.Factory.StartNewOnDifferentThread(() => handler.Raise(sender, e));
    }
    
    public static Task StartNewOnDifferentThread(this TaskFactory taskFactory, Action action) {
        return taskFactory.StartNew(action: action, cancellationToken: new CancellationToken());
    }
    

    Usage:

    public static Test() {
         myEventHandler.RaiseOnDifferentThread(null, EventArgs.Empty);
    }
    

    The cancellationToken is necessary to guarantee StartNew() actually uses a different thread, as explained here.

提交回复
热议问题