public FrmMainScreen()
{
InitializeComponent();
_schedulerFactory = new StdSchedulerFactory();
}
private void FrmMainScreen_Load(object sender, EventArgs e)
{
start();
}
private readonly ISchedulerFactory _schedulerFactory;
private IScheduler _scheduler;
private async void start()
{
_scheduler = await _schedulerFactory.GetScheduler();
await _scheduler.Start();
int settime = 20;
var trigger = TriggerBuilder.Create()
.WithSimpleSchedule(x => x.WithIntervalInSeconds(settime).RepeatForever())
.Build();
var jobDetail = JobBuilder.Create<Jobs>()
.WithIdentity("Myjob", "group")
.Build();
await _scheduler.ScheduleJob(jobDetail, trigger);
}
public class Jobs : IJob
{
public Task Execute(IJobExecutionContext context)
{
return Task.Run(async () =>
{
//这种情况下就不能运行
await new FrmMainScreen().Test(12);
});
}
}
// 将按钮的Click事件,可以正常运行
private async void button2_Click(object sender, EventArgs e)
{
await Test(12);
}
public async Task Test(int m)
{
int result = await TimeConsumingMethodAsnyc(m);
MessageBox.Show(result.ToString());
}
// 用async方法包装耗时函数
private async Task<int> TimeConsumingMethodAsnyc(int arg)
{
return await Task.Run(() => TimeConsumingMethod(arg));
}
// 耗时函数
private int TimeConsumingMethod(int arg)
{
Thread.Sleep(5000); // 模拟耗时过程
// Task.Delay(5000);
return arg; // 有返回值
}
}
去掉Test方法中MessageBox.Show()试试
不行的
自己解决。定义有问题