C# windows服务中的多线程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11985308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:58:08  来源:igfitidea点击:

Multiple threads in windows service

c#multithreadingtimerwindows-servicesthread-safety

提问by k-s

I have windows project and one form which have timer for each 5 seconds.

我有 Windows 项目和一个表格,每 5 秒有一个计时器。

It calls and processes methods from request named table time wise and condition wise.

它从名为表的时间明智和条件明智的请求中调用和处理方法。

But I have some methods types which takes too much time to respond and want those methods in separate thread. So that I can run those both request types in separate threads and syncs.

但是我有一些方法类型需要太多时间来响应并希望在单独的线程中使用这些方法。这样我就可以在单独的线程和同步中运行这两种请求类型。

How can I do separate those both using thread -- multi async threads?

如何使用线程将它们分开 - 多异步线程?

回答by Tudor

I recommend you look at the .NET 4.0 Taskclass. Firing full threads every time might be overkill. Tasks, together with timers use the underlying thread pool to execute work in parallel.

我建议您查看 .NET 4.0Task类。每次都触发完整的线程可能有点矫枉过正。任务与定时器一起使用底层线程池并行执行工作。

Using a Taskis as simple as:

使用 aTask非常简单:

Task t = Task.Factory.StartNew(
       () => 
       {
           // task code here
       });

回答by TheGeekZn

using System;
using System.Threading;

class Program
{
    static void Main()
    {
    Thread thread1 = new Thread(new ThreadStart(A));
    Thread thread2 = new Thread(new ThreadStart(B));
    thread1.Start();
    thread2.Start();
    thread1.Join();
    thread2.Join();
    }

    static void A()
    {
    Thread.Sleep(100);
    Console.WriteLine('A');
    }

    static void B()
    {
    Thread.Sleep(1000);
    Console.WriteLine('B');
    }
}

Threading Tutorial

线程教程