C# Windows Forms - outputting info to a textbox without crashing [closed]
In a Windows Forms app, I am using Quartz.NET to run some tasks every few minutes. Previously, this application was a console application that was invoked based on a schedule but for various reasons this wasn't ideal - back then all debug info was outputted to the console.
In this version, I need a way to show the debug information for a job on the user's screen. My initial idea was a new form that is shown when a job is run, and all debug information is appended to a multiline textbox on that form. However, this doesn't work as most of the app seems to crash when I do this.
Any other ideas?
EDIT: Sorry for any confusion. This is what's called when a job executes:
public virtual void Execute(JobExecutionContext context)
{
RunJob jobForm = new RunJob();
jobForm.Show();
jobForm.JobLabel = context.JobDetail.JobDataMap.G开发者_如何转开发etString("Name");
for (int i = 0; i < 100; i++)
{
jobForm.WriteLine(i.ToString());
}
jobForm.Hide();
}
And this is the contents of the 'RunJob' form:
public partial class RunJob : Form
{
public string JobLabel
{
get
{
return lblJobName.Text;
}
set
{
lblJobName.Text = value;
}
}
public void WriteLine(string text)
{
textBox1.AppendText(text + Environment.NewLine);
}
public RunJob()
{
InitializeComponent();
}
}
Basically, the RunJob window freezes when the text is being appended, when ideally it'd just add the text smoothly. I understand 'crash' was a very poor choice of word! My excuse is that it's early in the morning, ahem
i dont see anything wrong in above code that could lead it to deadlock or whatever it is, except this line: jobForm.JobLabel = context.JobDetail.JobDataMap.GetString("Name");
what does this line does, there must be something wrong in this line,
try putting some hard coded string instead of context.JobDetail.JobDataMap.GetString("Name");
and tell me if it still doesn't work.
Job and UI form should obviously be at separate threads. Job thread should write to the form and then close it when unneeded.
Presuming you have an Action action that is invoked on UI thread:
public virtual void Execute(JobExecutionContext context)
{
RunJob jobForm;
var name = context.JobDetail.JobDataMap.GetString("Name");
action(()=> { jobForm = new RunJob(); jobForm.Show(); jobForm.JobLabel = name;});
for (int i = 0; i < 100; i++)
{
var txt = i.ToString();
action(()=>{ jobForm.WriteLine(txt); });
}
action(()=> { jobForm.Hide(); });
}
精彩评论