【问题标题】:i want to execute a method several time in parallel while my app is runing我想在我的应用程序运行时并行执行一个方法
【发布时间】:2018-03-27 15:28:16
【问题描述】:

我有一个使用 WPF 的 c# 应用程序。我有一个方法 notification(); (如果我的数据库中有一个即将到来的约会显示通知)并且我想在我的应用程序运行时并行执行它几次(不停止),以便它可以随时检查数据库! 我在网上搜索并尝试了许多解决方案,例如线程,计时器,但它只并行执行一次!

public partial class MenuPrincipal : Window
{
    public MenuPrincipal()
    {
        InitializeComponent();
        UserControl usc = new Menu(ListRDV);
        SelectionGrid.Children.Add(usc);
        usc.VerticalAlignment = VerticalAlignment.Stretch;
        usc.HorizontalAlignment = HorizontalAlignment.Stretch;
        WindowStartupLocation = WindowStartupLocation.CenterScreen;
        Globals.TempcalculNotif = 60;
        Globals.TempRappelRDV = 15;
        Thread thrdNotif = new Thread(notification);
        thrdNotif.Start();
    }

    private void notification()
    {
            MessageBox.Show("calcul notif");
            string con = $@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\MCDatabase.mdf;Integrated Security=True";
            MCDataClassDataContext dataClass = new MCDataClassDataContext(con);
            IQueryable<RendezVous> NotifRdv = (from rendezVous in dataClass.RendezVous
                                               orderby rendezVous.Date
                                               select rendezVous);
            int cpt = 0;
            if (NotifRdv.Count() != 0)
            {
                foreach (RendezVous rdv in NotifRdv)
                {
                    string dateRdv, dateAJRD;
                    dateRdv = rdv.Date.ToString().Substring(0, 10);
                    dateAJRD = DateTime.Today.ToString().Substring(0, 10);
                    if (string.Compare(dateRdv, dateAJRD) == 0)
                    {
                        DateTime t1 = (DateTime)rdv.Date;
                        DateTime t2 = DateTime.Now;
                        TimeSpan t = t2 - t1;
                        if (t.TotalMinutes < Globals.TempRappelRDV)
                        {
                            if (rdv.IdPatient != 0)
                            {
                                if (rdv.Important == true)
                                {
                                    TextBlock TextRDV = new TextBlock();
                                     IQueryable<Patient> patientRDV = (from patient in dataClass.Patient
                                                                       where rdv.IdPatient == patient.Id
                                                                       select patient);
                                     IQueryable<Personne> personneRDV = (from personne in dataClass.Personne
                                                                         where patientRDV.First().IdPersonne == personne.Id
                                                                         select personne);
                                     string NomPatient = personneRDV.First().nom;
                                     string PrenomPatient = personneRDV.First().prenom;
                                     string heureRDV = rdv.Date.ToString().Substring(10, 9);
                                     TextRDV.Text = " RENDEZ VOUS DANS " + Globals.TempRappelRDV.ToString() + " min \n Patient: \n Nom: " + NomPatient + "\n Prenom: " + PrenomPatient + "\n Heure: " + heureRDV + "\n\t\t" + DateTime.Now.ToString();
                                     ListeNotif.Items.Add(TextRDV);
                                     System.Windows.Forms.NotifyIcon notif = new System.Windows.Forms.NotifyIcon();
                                     notif.Visible = true;
                                     notif.Icon = new System.Drawing.Icon(@"../../ressources/Icones/icones ico/logo_white.ico");
                                     notif.ShowBalloonTip(5000, "Medicare", "Vous un rendez vous important dans " + Globals.TempRappelRDV.ToString() + " minutes ", System.Windows.Forms.ToolTipIcon.Info);
                                     cpt++;
                                }
                            }
                        }
                    }
                }
            }
    }
}

【问题讨论】:

  • 为什么你认为线程会不断地执行方法?线程将在此方法返回的那一刻结束。
  • 你可能想尝试减少你的Arrow Code
  • 是的,我明白这一点,我试图找到一个解决方案来执行它几次或每分钟一次,例如......

标签: c# multithreading timer task


【解决方案1】:

我认为Thread类不是在后台执行代码的推荐方式,即使你只创建一个线程并继续使用它。你可以使用TaskFactory创建一个长时间运行的Task。之后,您可以在此处添加while(true) 循环以继续运行逻辑notification

//This should be stored in the resources, or some kind of configuration class
        public string con = $@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename={System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)}\MCDatabase.mdf;Integrated Security=True";

您可以在构造函数中创建任务。

public MenuPrincipal()
{
    InitializeComponent();
    UserControl usc = new Menu(ListRDV);
    SelectionGrid.Children.Add(usc);
    usc.VerticalAlignment = VerticalAlignment.Stretch;
    usc.HorizontalAlignment = HorizontalAlignment.Stretch;
    WindowStartupLocation = WindowStartupLocation.CenterScreen;
    Globals.TempcalculNotif = 60;
    Globals.TempRappelRDV = 15;
    Task.Factory.StartNew(notification, TaskCreationOptions.LongRunning);
}

如您所见,我告诉调度程序,这个任务是一个长期运行的任务。

private async void notification()
        {

            MCDataClassDataContext dataClass = new MCDataClassDataContext(con);
            while (true)
            {
                await Task.Delay(TimeSpan.FromSeconds(3));

                IQueryable<RendezVous> NotifRdv = (from rendezVous in dataClass.RendezVous
                                                   orderby rendezVous.Date
                                                   select rendezVous);
                int cpt = 0;
                if (NotifRdv.Count() != 0)
                {

                    foreach (RendezVous rdv in NotifRdv)
                    {
                        string dateRdv, dateAJRD;
                        dateRdv = rdv.Date.ToString().Substring(0, 10);
                        dateAJRD = DateTime.Today.ToString().Substring(0, 10);
                        if (string.Compare(dateRdv, dateAJRD) == 0)
                        {
                            DateTime t1 = (DateTime)rdv.Date;
                            DateTime t2 = DateTime.Now;
                            TimeSpan t = t2 - t1;
                            if (t.TotalMinutes < Globals.TempRappelRDV)
                            {
                                if (rdv.IdPatient != 0)
                                {
                                    if (rdv.Important == true)
                                    {
                                        TextBlock TextRDV = new TextBlock();
                                        IQueryable<Patient> patientRDV = (from patient in dataClass.Patient
                                                                          where rdv.IdPatient == patient.Id
                                                                          select patient);
                                        IQueryable<Personne> personneRDV = (from personne in dataClass.Personne
                                                                            where patientRDV.First().IdPersonne == personne.Id
                                                                            select personne);
                                        string NomPatient = personneRDV.First().nom;
                                        string PrenomPatient = personneRDV.First().prenom;
                                        string heureRDV = rdv.Date.ToString().Substring(10, 9);
                                        TextRDV.Text = " RENDEZ VOUS DANS " + Globals.TempRappelRDV.ToString() + " min \n Patient: \n Nom: " + NomPatient + "\n Prenom: " + PrenomPatient + "\n Heure: " + heureRDV + "\n\t\t" + DateTime.Now.ToString();
                                        ListeNotif.Items.Add(TextRDV);
                                        System.Windows.Forms.NotifyIcon notif = new System.Windows.Forms.NotifyIcon();
                                        notif.Visible = true;
                                        notif.Icon = new System.Drawing.Icon(@"../../ressources/Icones/icones ico/logo_white.ico");
                                        notif.ShowBalloonTip(5000, "Medicare", "Vous un rendez vous important dans " + Globals.TempRappelRDV.ToString() + " minutes ", System.Windows.Forms.ToolTipIcon.Info);
                                        cpt++;
                                    }
                                }
                            }
                        }
                    }
                }

        }

每当您想与UI 线程拥有的对象进行通信时,您都可以使用Dispatcher。虽然,我真的不知道你为什么要以这种方式编写代码。但我只是为您的具体问题提供了答案。

【讨论】:

    【解决方案2】:

    我建议您的notification 函数应该输入while(true) 以便继续执行逻辑并继续检查

    private void notification()
    {
        //do your logic here
    
        Thread.Sleep(1000); //this time is every second (1000 ms)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多