如图,上面的命令将每隔10800000毫秒执行一次。如果中途想终止,怎么办?最好的办法就是将时间分片为每2秒,或者几秒,缩短执行睡眠的时间,而不是直接让线程休眠10800000毫秒,参考如下解决方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;
namespace WpfAppVPN_active
{
public partial class MainWindow : Window
{
static bool isRun = false;
/// <summary>
/// 任务剩余存活时长,毫秒
/// </summary>
static int live_millseconds = 0;
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// 运行
/// </summary>
public void RunTask()
{
isRun = true;
Task task = new Task(() =>
{
while (isRun)
{
ShowMsg($"任务{Thread.CurrentThread.ManagedThreadId}将在{live_millseconds}毫秒后执行...");
if (live_millseconds > 0)
{
goto TO_SLEEP;
}
DO_TASK:
//执行的命令
string urlExe = string.Empty;
Dispatcher.Invoke(() =>
{
urlExe = txtUrl.Text;
});
try
{
string exe = urlExe.Split(' ')[0];
string args = urlExe.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length > 1 ?
urlExe.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1] : "";
if (string.IsNullOrWhiteSpace(args))
{
System.Diagnostics.Process.Start(exe);
}
else
{
System.Diagnostics.Process.Start(exe, args);
}
Dispatcher.InvokeAsync(() =>
{
string msg = $"{Thread.CurrentThread.ManagedThreadId}执行成功";
ShowMsg(msg);
});
}
catch (Exception ex)
{
var ex1 = ex.InnerException ?? ex;
string msg = "出错:" + ex1.Message;
ShowMsg(msg);
}
TO_SLEEP:
if (live_millseconds > 2000)
{
Thread.Sleep(2000);
live_millseconds -= 2000;
}
else
{
try
{
Thread.Sleep(live_millseconds);
Dispatcher.Invoke(() =>
{
//重置存活时间
if (int.TryParse(txtTimeSpan.Text.Trim(), out live_millseconds))
{ }
});
if (isRun)
{
//开始执行命令
goto DO_TASK;
}
}
catch (Exception ex)
{
var ex1 = ex.InnerException ?? ex;
ShowMsg("DO_TASK异常," + ex1.Message);
}
}
}
ShowMsg($"任务{Thread.CurrentThread.ManagedThreadId}结束");
Dispatcher.InvokeAsync(() => {
btnStart.IsEnabled = true;
});
}, TaskCreationOptions.LongRunning);
task.Start();
}
private static object obj = new object();
//确定,开始
private void Button_Click(object sender, RoutedEventArgs e)
{
//isRun = false;
lock (obj)
{
if (!isRun)
{
//间隔时间,毫秒
if (int.TryParse(txtTimeSpan.Text.Trim(), out live_millseconds))
{
btnStart.IsEnabled = false;
ShowMsg("开始 ");
RunTask();
}
}
}
}
//停止
private void Stop_Click(object sender, RoutedEventArgs e)
{
if (isRun)
{
btnStart.IsEnabled = false;
isRun = false;
live_millseconds = 0;
ShowMsg("停止中...");
}
}
/// <summary>
/// 显示消息
/// </summary>
/// <param name="msg"></param>
private void ShowMsg(string msg)
{
if (string.IsNullOrWhiteSpace(msg))
{
return;
}
string msg2 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "," + msg;
Dispatcher.Invoke(new Action(() =>
{
listBox1.Items.Add(msg2);
listBox1.ScrollIntoView(msg2);
}));
}
}
}