简体   繁体   English

Windows服务中的另一个进程正在使用的文件

[英]File being used by another process in windows service

I have written following code which runs fine but problem is that sometimes it gives me file being used by another process these two jobs are accessing and writing the same file. 我编写了下面的代码,该代码运行良好,但问题是有时它使我的file being used by another process这两个作业正在访问并写入同一文件。 ClickProfileJob runs first and repeats after 5 seconds and then the second job ClickLikeJob according to schedule of 5 seconds. ClickProfileJob首先运行,并在5秒后重复,然后根据5秒的计划运行第二个作业ClickLikeJob I have seen couple of solutions which had suggested the same using technique which I have coded below. 我已经看到了一些解决方案,这些解决方案提出了我下面编码的相同using技术。

    using Quartz;
    using System;
    using System.IO;
    using Topshelf;
    using Topshelf.Quartz;

    namespace FinyaConsole
    {
     class Program
     {
        static void Main(string[] args)
        {
            userCreds creds = new userCreds();

            if (creds.checkUser().Length > 3)
            {
                HostFactory.Run(x =>
                {
                    x.Service<GiveHeartsService>(s =>
                    {
                        s.WhenStarted(service => service.OnStart());
                        s.WhenStopped(service => service.OnStop());
                        s.ConstructUsing(() => new GiveHeartsService());

                        s.ScheduleQuartzJob(q =>
                            q.WithJob(() =>
                                JobBuilder.Create<ClickProfileJob>().Build())
                                .AddTrigger(() => TriggerBuilder.Create()
                                    .WithSimpleSchedule(b => b
                                        .WithIntervalInSeconds(5)
                                        .RepeatForever())
                                    .Build()));

                        s.ScheduleQuartzJob(q =>
                            q.WithJob(() =>
                                JobBuilder.Create<ClickLikeJob>().Build())
                                .AddTrigger(() => TriggerBuilder.Create()
                                    .WithSimpleSchedule(b => b
                                        .WithIntervalInSeconds(5)
                                        .RepeatForever())
                                    .Build()));


                    });

                    //.DependsOnEventLog()

                    x.RunAsLocalSystem()
                        .StartAutomaticallyDelayed()
                        .EnableServiceRecovery(rc => rc.RestartService(1));

                    x.SetServiceName("FinyaHearts");
                    x.SetDisplayName("FinyaHearts");
                    x.SetDescription("This is a service.");
                });
            }
        }
    }
        public class ClickProfileJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                try
                {
                    using (StreamWriter sw = new StreamWriter(".\\visits_to_others.txt", true))
                    {

                        //Write a line of text
                        sw.WriteLine($"[{DateTime.Now}] Welcome from ClickProfileJob!");
                        Console.WriteLine($"[{DateTime.Now}] Welcome from ClickProfileJob!");
                        //System.IO.File.WriteAllText(@"path\visit_users.txt", userLink);
                        //Close the file
                        sw.Flush();
                        sw.Dispose();
                        sw.Close();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                }
                finally
                {
                    //Console.WriteLine("Executing finally block.");
                }
            }
        }

        public class ClickLikeJob : IJob
        {
            public void Execute(IJobExecutionContext context)
            {
                try
                {
                    using (StreamWriter sw = new StreamWriter(".\\visits_to_others.txt", true))
                    {

                        //Write a line of text
                        sw.WriteLine($"[{DateTime.Now}] Welcome from ClickLikeJob!");
                        Console.WriteLine($"[{DateTime.Now}] Welcome from ClickLikeJob!");
                        //System.IO.File.WriteAllText(@"path\visit_users.txt", userLink);
                        //Close the file
                        sw.Flush();
                        sw.Dispose();
                        sw.Close();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                }
                finally
                {
                    //Console.WriteLine("Executing finally block.");
                }
            }
        }
    }

This is not a Quartz specific problem. 这不是Quartz特有的问题。 You can use a SemaphoreSlim or better a simple lock . 您可以使用SemaphoreSlim或更好的简单lock Just create a base job and derive your other Jobs from it. 只需创建一个基本作业,然后从中导出其他作业即可。 Then lock the LockObject in both Jobs. 然后在两个作业中锁定LockObject

public abstract class LockableJobBase
{
    protected static object LockObject = new object();
}


public class ClickProfileJob : LockableJobBase, IJob
{
    public void Execute(IJobExecutionContext context)
    {
        try
        {
            lock (LockObject)
            {
                using (StreamWriter sw = new StreamWriter(".\\visits_to_others.txt", true))
                {
                    // your sw stuff
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            //Console.WriteLine("Executing finally block.");
        }
    }
}

public class ClickLikeJob : LockableJobBase, IJob
{
    public void Execute(IJobExecutionContext context)
    {
        try
        {
            lock (LockObject)
            {
                using (StreamWriter sw = new StreamWriter(".\\visits_to_others.txt", true))
                {
                    // your sw stuff
                }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            //Console.WriteLine("Executing finally block.");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 写入C#中另一个进程(Windows服务)正在使用的文件 - Write to a file that is being used by another process (Windows Service) in C# 该进程无法访问文件&#39;C:\\ PCLtoMove \\ print.pcl&#39;,因为它正在被另一个进程使用。 Windows服务 - The process cannot access the file 'C:\PCLtoMove\print.pcl' because it is being used by another process. Windows service Windows 服务文件流给出 System.IO.IOException:进程无法访问文件“文件名”,因为它正被另一个进程使用 - Windows Service Filestream giving System.IO.IOException: The process cannot access the file "filename" because it is being used by another process 如何访问Windows中另一个进程正在使用的文件? - How to access a file that is being used by another process in Windows? 文件正在被另一个进程使用 - file being used by another process 文件正由另一个进程使用 - File is being used by another process 文件正被另一个进程使用 - File is being used by another process Windows 8.1应用程序-该进程无法访问文件,因为该文件正在被另一个进程使用 - Windows 8.1 app - The process cannot access the file because it is being used by another process 该进程无法访问该文件,因为该文件正在被另一个进程使用。” Windows应用程序开发 - The process cannot access the file because it is being used by another process” Windows Application Development 无法更新我自己的 windows 服务,因为它正被另一个进程使用 - Cannot update my own windows service because it is being used by another process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM