Windows form elements arent inherited inside method that is created on triggered job (C#)

47 views Asked by At

in this windows form app i use this Scheduler from Quartz.NET to trigger a job on certain time. Code works fine but i have an issue when executing the job and need to call something from the form outside the method created by the job. The (textBox1.Text) isnt inherited inside the method that is created on triggered job. (i think it has to do with the fact that Scheduler class is public async, any explanation is welcome)

namespace TaxControl
{

    public partial class TaxControl : Form
    {

.........................................

public class Scheduler
        {
            public async void Start()
            {
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
                IScheduler scheduler = await schedulerFactory.GetScheduler();
                await scheduler.Start();

                IJobDetail job = JobBuilder.Create<Job>()
                 .WithIdentity("job", "group1")
                 .Build();
            
                ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("job", "group1")
                .WithCronSchedule("0 36 18 * * ?")
                .Build();
                await scheduler.ScheduleJob(job, trigger);
            }
        }

        public class Job : IJob
        {
            Task IJob.Execute(IJobExecutionContext context)
            {
                if (context == null)
                {
                    throw new ArgumentNullException(nameof(context));
                }

                Task taskA = new Task(() => InfoControl());

                taskA.Start();
                return taskA;
            }
            public void InfoControl()
            {
                MessageBox.Show(textBox1.Text);
            }
        }
1

There are 1 answers

0
vgru On

There are several problems with this code:

  1. obviously, the Job class doesn't have the reference to this TextBox instance. This would normally be solved by writing a Job constructor which accepts the TextBox reference.

  2. However, to make Quartz.Net instantiate the job with parameterized constructor, you'll need to inject it using something like this, which is also often done using DI like this, or this.

  3. Accessing Control.Text on a non-UI thread will throw an exception, so this means you will need to access the actual property by dispatching the call to the UI thread, or just simplify the whole thing by passing a simple string to your Job.

You can also pass a Func<string> to the job's constructor, i.e. a function which returns a string. This function also needs to do the UI access in a thread safe matter, but it will decouple the job logic from the actual UI.