【发布时间】:2019-07-09 15:40:13
【问题描述】:
我有一些非常简单的代码试图对现有脚本进行多线程处理。
在 Visual Studio 中检查履带窗口并调用 Thread.CurrentThread.ManagedThreadId 时,它始终报告为与启动进程相同的线程。结束时,它会报告一个不同的线程 ID。
线程似乎确实在异步执行任务,但是 Visual Studio 的日志记录和输出让我不这么认为。
请有人澄清发生了什么,如果我在我的方法中犯了错误?
namespace ResolveGoogleURLs
{
class Program
{
public static void Main(string[] args)
{
HomeController oHC = new HomeController();
}
}
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ResolveGoogleURLs
{
class HomeController
{
public static int MaxJobs = 5;
public static int RecordsPerJob = 1000;
public static List<Task> TaskList = new List<Task>(MaxJobs);
public HomeController()
{
CreateJobs();
MonitorTasks();
}
public void MonitorTasks()
{
while (1 == 1)
{
Task.WaitAny(TaskList.ToArray());
TaskList.RemoveAll(x => x.IsCompleted);
Console.WriteLine("Task complete! Launching new...");
CreateJobs();
}
}
public async Task CreateJob()
{
Console.WriteLine("Thread {0} - Start", Thread.CurrentThread.ManagedThreadId);
// read in results from sql
await Task.Delay(10000);
Console.WriteLine("Thread {0} - End", Thread.CurrentThread.ManagedThreadId);
}
public void CreateJobs()
{
while (TaskList.Count < MaxJobs)
{
TaskList.Add( CreateJob() );
}
}
}
}
输出:
> Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 4 - End
Thread 5 - End
Thread 4 - End
Thread 6 - End
Thread 8 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Thread 7 - End
Thread 6 - End
Thread 5 - End
Thread 4 - End
Thread 8 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 1 - Start
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Thread 10 - End
Thread 9 - End
Task complete! Launching new...
Thread 1 - Start
Thread 7 - End
Thread 4 - End
Thread 6 - End
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
Task complete! Launching new...
Thread 1 - Start
Thread 1 - Start
【问题讨论】:
-
code that's attempting to multi-thread- 不,这是not 尝试这样做。Same thread as starting the process. When ending it reports back a different thread id- 因为在控制台应用程序中,延续 does not have 在原始线程上运行。seem to be performing the task asynchronously, but the logging and output from visual studio are making me think otherwise- 请参阅 stackoverflow.com/q/37419572/11683 和 blog.stephencleary.com/2013/11/there-is-no-thread.html。 -
目前尚不清楚您获得的结果与您期望的结果有何不同。如果我没记错的话,这不是问题吗 - 为什么我会得到这个,不是那个?预期的结果是什么?我的期望是哪个线程启动任务以及哪个线程完成它会有点不可预测,这就是这个输出的样子。
-
任务!=线程;这在我看来是完全正确和预期的; 你希望它是什么样子,为什么?
-
您正在处理任务。任务不等同于线程。系统将在其可用的任何可用线程上执行任务,简而言之。
awaited 操作之后的异步方法中的任何代码都可能在任意线程上下文中执行,甚至可能不是线程池中的后台线程,这完全取决于等待操作的行为/性质...... -
执行异步不与创建线程同义。主要是为了避免不必要的线程。
标签: c# multithreading async-await