我正在使用以下代码来启动职位。
List<Thread> threads = new List<Thread>();
List<Job> foundedJobs = new List<Job>();
public void StartAllJobs()
{
try
{
if (CanExecuteJobs == false) return;
var jobs = GetAllTypesImplementingInterface(typeof(Job)); // get all job implementations of this assembly.
var enumerable = jobs as Type[] ?? jobs.ToArray();
if (jobs != null && enumerable.Any()) // execute each job
{
Job instanceJob = null;
var index = 0;
foreach (var job in enumerable)
{
if (IsRealClass(job)) // only instantiate the job its implementation is "real"
{
try
{
instanceJob = (Job)Activator.CreateInstance(job); // instantiate job by reflection
foundedJobs.Add(instanceJob);
var thread = new Thread(new ThreadStart(instanceJob.ExecuteJob))
{
IsBackground = true,
Name = "SID" + index
}; // create thread for this job execution method
thread.Start();// start thread executing the job
threads.Add(thread);
index++;
}
catch (Exception ex)
{
App.Logger.Error(ex);
}
}
}
}
}
catch (Exception ex)
{
App.Logger.Error(ex);
}
}
我如何在Job
稍后在其他课程中访问thread
课程?
我的意思是我们像这样创建Thread
var thread = new Thread(new ThreadStart(instanceJob.ExecuteJob))
{
IsBackground = true,
Name = "SID" + index
};
我可以以某种方式使用thread
访问instanceJob
吗?
谢谢!
答案 0 :(得分:1)
线程并没有真正与任何特定类相关联,并且它的ThreadStart
没有公开,所以给定一个线程,实际上并没有提取类上下文。
相反,它看起来像是需要创建一些字典,其中Thread
为关键字,而job
为值。然后,给定Thread
实例,您可以在字典中查询关联的job
实例。
Dictionary<Thread, Job> threads = new Dictionary<Thread, Job>();
List<Job> foundedJobs = new List<Job>();
public void StartAllJobs()
{
try
{
if (CanExecuteJobs == false) return;
var jobs = GetAllTypesImplementingInterface(typeof(Job)); // get all job implementations of this assembly.
var enumerable = jobs as Type[] ?? jobs.ToArray();
if (jobs != null && enumerable.Any()) // execute each job
{
Job instanceJob = null;
var index = 0;
foreach (var job in enumerable)
{
if (IsRealClass(job)) // only instantiate the job its implementation is "real"
{
try
{
instanceJob = (Job)Activator.CreateInstance(job); // instantiate job by reflection
foundedJobs.Add(instanceJob);
var thread = new Thread(new ThreadStart(instanceJob.ExecuteJob))
{
IsBackground = true,
Name = "SID" + index
}; // create thread for this job execution method
thread.Start();// start thread executing the job
threads.Add(thread, job);
index++;
}
catch (Exception ex)
{
App.Logger.Error(ex);
}
}
}
}
}
catch (Exception ex)
{
App.Logger.Error(ex);
}
}
在其他需要为线程工作的地方:
job = threads[myThreadInstance]; // Where myThreadInstance is an instance of Thread class...
答案 1 :(得分:1)
我建议使用.NET 4的Task<T>
来保存它,而不是使用Thread。然后,您可以直接在Job
:
Task<Job>
public List<Task<Job>> StartAllJobs()
{
if (CanExecuteJobs == false) return;
var jobs = GetAllTypesImplementingInterface(typeof(Job)); // get all job implementations of this assembly.
return jobs.Where(IsRealClass)
.Select(job => (Job)Activator.CreateInstance(job))
.Select(job => Task.Factory.StartNew(() => { job.ExecuteJob(); return job; }))
.ToList();
}
这将为您提供在作业的ExecuteJob
方法完成后将完成的任务列表,Task.Result
将是执行的作业。