예제 #1
0
        private static ThreadContext DoCreate(string name, Action <CancellationToken> action, bool isBackground)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken       token  = source.Token;
            var threadResult = new ThreadResult();
            var thread       = new Thread(() => ThreadAction(name, threadResult, action, token));

            thread.Name         = name;
            thread.IsBackground = isBackground;
            return(new ThreadContext(thread, source, threadResult));
        }
예제 #2
0
        public static ThreadContext Create(string name, Func <CancellationToken, Task> action, bool isBackground = true)
        {
            CancellationTokenSource source = new CancellationTokenSource();
            CancellationToken       token  = source.Token;
            var threadResult = new ThreadResult();
            var thread       = new Thread(() => ThreadAction(name, threadResult, (t) => action(t).Wait(), token));

            thread.Name         = name;
            thread.IsBackground = isBackground;
            return(new ThreadContext(thread, source, threadResult));
        }
예제 #3
0
        private static ThreadContext DoCreate(string name, Action <CancellationToken> action, bool isBackground, CancellationToken token = default)
        {
            CancellationTokenSource source       = new CancellationTokenSource();
            CancellationTokenSource linkedTokens = CancellationTokenSource.CreateLinkedTokenSource(source.Token, token);
            var threadResult = new ThreadResult();
            var thread       = new Thread(() => ThreadAction(name, threadResult, action, linkedTokens.Token))
            {
                Name         = name,
                IsBackground = isBackground
            };

            return(new ThreadContext(thread, source, threadResult));
        }
예제 #4
0
 private static void ThreadAction(string name, ThreadResult threadResult, Action <CancellationToken> action, CancellationToken token)
 {
     logger.Debug(() => $"Thread {name} is started.");
     try
     {
         action.Invoke(token);
     }
     catch (Exception e)
     {
         if (!token.IsCancellationRequested)
         {
             logger.Error(e, $"Thread {name} failed with error.");
             threadResult.Error = e;
         }
     }
     logger.Debug(() => $"Thread {name} is stopped.");
 }
예제 #5
0
 internal ThreadContext(Thread thread, CancellationTokenSource tokenSource, ThreadResult result)
 {
     this.thread      = thread;
     this.tokenSource = tokenSource;
     this.result      = result;
 }