【发布时间】:2020-02-09 05:33:50
【问题描述】:
我写了一个 Windows 服务。 下面是类内部定义的全局变量:
private static TimeSpan pollingInterval;
private static Thread regenerationThread;
private static ManualResetEvent quitThreadEvent;
private static ConcurrentQueue<KeyValuePair<string, string>> queue = new ConcurrentQueue<KeyValuePair<string, string>>();
这里是服务的启动方法:
internal static void Start()
{
pollingInterval = TimeSpan.FromSeconds(100);
quitThreadEvent = new ManualResetEvent(false);
regenerationThread = new Thread(doStart);
regenerationThread.Start();
}
这里是上面提到的doStart方法:
internal static void doStart()
{
queue.Enqueue(new KeyValuePair<string, string>("user1", "password1"));
queue.Enqueue(new KeyValuePair<string, string>("user2", "password2"));
queue.Enqueue(new KeyValuePair<string, string>("user3", "password3"));
while (!quitThreadEvent.WaitOne(pollingInterval))
{
// tempList isn't empty, I checked it putting logs here.
if (tempList.Length != 0)
{
var temp = new KeyValuePair<string, string>();
if (queue.TryDequeue(out temp))
{
string username = temp.Key;
string password = temp.Value;
// Method comes till here but doesn't execute the statement below and directly reach to end WriteToFile method.
Task.Run(async () =>
{
await tempFunc(username, password);
queue.Enqueue(new KeyValuePair<string, string>(username, password));
});
}
}
WriteToFile("End of Method");
}
}
我不确定为什么 Task.Run 不起作用。我已经放了日志,但它没有显示任何错误。我尝试将日志放在Task.run 中,但它没有显示这些日志。是我开始一个线程然后在里面调用Task.run的原因吗?
【问题讨论】:
-
你为什么不用
Task.Run()而不是线程? -
在这种情况下根本不需要Task.Run
-
我没听懂你。您是否建议而不是
regenerationThread = new Thread(doStart);和regenerationThread.Start();声明。使用Task.Run()启动方法doStart? @克林特 -
您的
DoStart()可以是async Task DoTask() -
@SirRufo,实际上我希望
tempFunc方法被异步调用多次,所以我认为Task.Run是这样做的正确方法吗?还是我在这里遗漏了什么?
标签: c# multithreading windows-services