threads that cannot be stoped property

im newbie in C#, want to make a small app that checks the disks and in case of write timeout or exceptions (disk disconnection or something) do the computer restart.
This code seems to be working normally when i run it – it simply writes to some txt file date every one second, but when i offline the disk and online it again it firstly goes correct and then stop working normally.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Timers;
using System.Collections;
public class Example
{
public static int failedCounter = 0;
public static int errorRestartThreshold = 5;
const int delayInMilliseconds = 1000;
const int diskThresholdGb = 20;
const string writeDirectoryName = "cdiskmonitorCheck";
const string writeFileName = "cdiskmonitorCheck.txt";
const string fullErrorDirectoryName = "c:\cdiskmonitorCheck";
const string fullErrorFileName = fullErrorDirectoryName +"\"+ "cdiskmonitorError.log";
public bool exceptionFlag = false;
public static void Main()
{
Example e = new Example();
e.OnStart();
}
public void OnStart()
{
//Thread t = new Thread(Listener);
foreach (var drive in DriveInfo.GetDrives())
{
if (drive.IsReady == true)
{
double totalSpace = drive.TotalSize;
int totalSpaceinGB = (int)(totalSpace / 1024 / 1024 / 1024);
if (totalSpaceinGB > diskThresholdGb)
{
string diskName = drive.Name;
Console.WriteLine(diskName);
if (diskName == "D:\")
{
Console.WriteLine("we start");
Thread t = new Thread(Listener);
t.Start(diskName);
}
}
}
}
Console.ReadLine();
}
private void Listener(object diskLetter)
{
Thread thread = null;
//diskLetter = "fff:";
string fullWriteFolderPath = diskLetter +writeDirectoryName;
string fullWriteFilePath = fullWriteFolderPath + "\" + writeFileName;
while (true)
{
var task = Task.Run(() =>
{
exceptionFlag = false;
DateTime start = DateTime.Now;
thread = Thread.CurrentThread;
try
{
//create directory
if (!Directory.Exists(fullWriteFolderPath))
{
Directory.CreateDirectory(fullWriteFolderPath);
}
Console.WriteLine(fullWriteFilePath);
Console.WriteLine(start.ToString("MM/dd/yyyy hh:mm:ss.fff"));
using (StreamWriter sw = new StreamWriter(fullWriteFilePath))
{
sw.WriteLine(start.ToString("MM/dd/yyyy hh:mm:ss.fff"));
}
failedCounter = 0;
}
catch (Exception ex)
{
exceptionFlag = true;
//break;
Console.WriteLine(ex.ToString());
}
DateTime finish = DateTime.Now;
System.TimeSpan diff = finish - start;
int diffInMilliseconds = (int)diff.TotalMilliseconds;
//we wait for sometime to be 1 second
if (diffInMilliseconds < delayInMilliseconds)
{
Task.Delay((delayInMilliseconds - diffInMilliseconds)).Wait();
//Console.WriteLine((delayInMilliseconds - diffInMilliseconds));
}
});
//Check if task is finished.
bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(1200));
//Console.WriteLine(isCompletedSuccessfully);
DateTime current = DateTime.Now;
if (!Directory.Exists(fullErrorDirectoryName))
{
Directory.CreateDirectory(fullErrorDirectoryName);
}
if (exceptionFlag)
{
current = DateTime.Now;
thread.Abort(true);
failedCounter++;
Console.WriteLine("Exception writting to file");
using (StreamWriter sw = File.AppendText(fullErrorFileName))
{
sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " exception, counter:" + failedCounter.ToString());
}
}
else
{
if (!isCompletedSuccessfully)
{
current = DateTime.Now;
failedCounter++;
Console.WriteLine("Timeoutted writting to file");
thread.Abort(true);
using (StreamWriter sw = File.AppendText(fullErrorFileName))
{
sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " timeoutted, counter:" + failedCounter.ToString());
}
}
else
{
failedCounter = 0;
Console.WriteLine("Task completed during period");
}
}
Console.WriteLine(failedCounter);
if (failedCounter >= errorRestartThreshold)
{
current = DateTime.Now;
using (StreamWriter sw = File.AppendText(fullErrorFileName))
{
sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " we restart server., counter:" + failedCounter.ToString());
}
}
}
}
}
</code>
<code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Threading; using System.Timers; using System.Collections; public class Example { public static int failedCounter = 0; public static int errorRestartThreshold = 5; const int delayInMilliseconds = 1000; const int diskThresholdGb = 20; const string writeDirectoryName = "cdiskmonitorCheck"; const string writeFileName = "cdiskmonitorCheck.txt"; const string fullErrorDirectoryName = "c:\cdiskmonitorCheck"; const string fullErrorFileName = fullErrorDirectoryName +"\"+ "cdiskmonitorError.log"; public bool exceptionFlag = false; public static void Main() { Example e = new Example(); e.OnStart(); } public void OnStart() { //Thread t = new Thread(Listener); foreach (var drive in DriveInfo.GetDrives()) { if (drive.IsReady == true) { double totalSpace = drive.TotalSize; int totalSpaceinGB = (int)(totalSpace / 1024 / 1024 / 1024); if (totalSpaceinGB > diskThresholdGb) { string diskName = drive.Name; Console.WriteLine(diskName); if (diskName == "D:\") { Console.WriteLine("we start"); Thread t = new Thread(Listener); t.Start(diskName); } } } } Console.ReadLine(); } private void Listener(object diskLetter) { Thread thread = null; //diskLetter = "fff:"; string fullWriteFolderPath = diskLetter +writeDirectoryName; string fullWriteFilePath = fullWriteFolderPath + "\" + writeFileName; while (true) { var task = Task.Run(() => { exceptionFlag = false; DateTime start = DateTime.Now; thread = Thread.CurrentThread; try { //create directory if (!Directory.Exists(fullWriteFolderPath)) { Directory.CreateDirectory(fullWriteFolderPath); } Console.WriteLine(fullWriteFilePath); Console.WriteLine(start.ToString("MM/dd/yyyy hh:mm:ss.fff")); using (StreamWriter sw = new StreamWriter(fullWriteFilePath)) { sw.WriteLine(start.ToString("MM/dd/yyyy hh:mm:ss.fff")); } failedCounter = 0; } catch (Exception ex) { exceptionFlag = true; //break; Console.WriteLine(ex.ToString()); } DateTime finish = DateTime.Now; System.TimeSpan diff = finish - start; int diffInMilliseconds = (int)diff.TotalMilliseconds; //we wait for sometime to be 1 second if (diffInMilliseconds < delayInMilliseconds) { Task.Delay((delayInMilliseconds - diffInMilliseconds)).Wait(); //Console.WriteLine((delayInMilliseconds - diffInMilliseconds)); } }); //Check if task is finished. bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(1200)); //Console.WriteLine(isCompletedSuccessfully); DateTime current = DateTime.Now; if (!Directory.Exists(fullErrorDirectoryName)) { Directory.CreateDirectory(fullErrorDirectoryName); } if (exceptionFlag) { current = DateTime.Now; thread.Abort(true); failedCounter++; Console.WriteLine("Exception writting to file"); using (StreamWriter sw = File.AppendText(fullErrorFileName)) { sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " exception, counter:" + failedCounter.ToString()); } } else { if (!isCompletedSuccessfully) { current = DateTime.Now; failedCounter++; Console.WriteLine("Timeoutted writting to file"); thread.Abort(true); using (StreamWriter sw = File.AppendText(fullErrorFileName)) { sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " timeoutted, counter:" + failedCounter.ToString()); } } else { failedCounter = 0; Console.WriteLine("Task completed during period"); } } Console.WriteLine(failedCounter); if (failedCounter >= errorRestartThreshold) { current = DateTime.Now; using (StreamWriter sw = File.AppendText(fullErrorFileName)) { sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " we restart server., counter:" + failedCounter.ToString()); } } } } } </code>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Timers;
using System.Collections;


public class Example
{
    public static int failedCounter = 0;
    public static int errorRestartThreshold = 5;


    const int delayInMilliseconds = 1000;
    const int diskThresholdGb = 20;
    const string writeDirectoryName = "cdiskmonitorCheck";
    const string writeFileName = "cdiskmonitorCheck.txt";

    const string fullErrorDirectoryName = "c:\cdiskmonitorCheck";
    const string fullErrorFileName = fullErrorDirectoryName +"\"+ "cdiskmonitorError.log";



    public bool exceptionFlag = false;

    public static void Main()
    {
        Example e = new Example();
        e.OnStart();

    }
    public void OnStart()
    {

        //Thread t = new Thread(Listener);
        foreach (var drive in DriveInfo.GetDrives())
        {
            if (drive.IsReady == true)
            {
                double totalSpace = drive.TotalSize;
                int totalSpaceinGB = (int)(totalSpace / 1024 / 1024 / 1024);

                if (totalSpaceinGB > diskThresholdGb)
                {
                    string diskName = drive.Name;
                    Console.WriteLine(diskName);
                    if (diskName == "D:\")
                    {
                        Console.WriteLine("we start");
                        Thread t = new Thread(Listener);
                        t.Start(diskName);
                    }

                }
            }

        }
        Console.ReadLine();

    }

    private void Listener(object diskLetter)
    {
        Thread thread = null;

        //diskLetter = "fff:";

        string fullWriteFolderPath = diskLetter +writeDirectoryName;
        string fullWriteFilePath = fullWriteFolderPath + "\" + writeFileName;

        

        while (true)
        {
            var task = Task.Run(() =>
            {
                exceptionFlag = false;
                DateTime start = DateTime.Now;
                thread = Thread.CurrentThread;
                
                try
                {
                    //create directory
                    if (!Directory.Exists(fullWriteFolderPath))
                    {
                        Directory.CreateDirectory(fullWriteFolderPath);
                    }
                    Console.WriteLine(fullWriteFilePath);

                    Console.WriteLine(start.ToString("MM/dd/yyyy hh:mm:ss.fff"));
                    using (StreamWriter sw = new StreamWriter(fullWriteFilePath))
                        {
                            sw.WriteLine(start.ToString("MM/dd/yyyy hh:mm:ss.fff"));
                        }
                    
                    failedCounter = 0;
                }
                catch (Exception ex)
                {
                    exceptionFlag = true;
                    //break;
                    Console.WriteLine(ex.ToString());

                }

                DateTime finish = DateTime.Now;

                System.TimeSpan diff = finish - start;
                int diffInMilliseconds = (int)diff.TotalMilliseconds;

                //we wait for sometime to be 1 second
                if (diffInMilliseconds < delayInMilliseconds)
                {
                    Task.Delay((delayInMilliseconds - diffInMilliseconds)).Wait();
                    //Console.WriteLine((delayInMilliseconds - diffInMilliseconds));
                }

            });


            //Check if task is finished.

            bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(1200));
            //Console.WriteLine(isCompletedSuccessfully);
            DateTime current = DateTime.Now;
            if (!Directory.Exists(fullErrorDirectoryName))
            {
                Directory.CreateDirectory(fullErrorDirectoryName);
            }

            if (exceptionFlag)
            {
                current = DateTime.Now;
                thread.Abort(true);
                failedCounter++;
                Console.WriteLine("Exception writting to file");
                using (StreamWriter sw = File.AppendText(fullErrorFileName))
                {
                    sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " exception, counter:" + failedCounter.ToString());
                }
            }
            else
            {
                if (!isCompletedSuccessfully)
                {

                    current = DateTime.Now;
                    failedCounter++;
                    Console.WriteLine("Timeoutted writting to file");
                    thread.Abort(true);

                    using (StreamWriter sw = File.AppendText(fullErrorFileName))
                    {
                        sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " timeoutted, counter:" + failedCounter.ToString());
                    }

                }
                else
                {
                    failedCounter = 0;
                    Console.WriteLine("Task completed during period");
                }

            }

            Console.WriteLine(failedCounter);



            if (failedCounter >= errorRestartThreshold)
            {
                current = DateTime.Now;
                using (StreamWriter sw = File.AppendText(fullErrorFileName))
                {
                    sw.WriteLine(current.ToString("MM/dd/yyyy hh:mm:ss.fff") + " we restart server., counter:" + failedCounter.ToString());
                }
            }
            

        }

    }

}





working example

For example when i disconnect the disk D and then in few moments connect it back it still cant write to it and generates wrong result

i seaching for the answer for 2 weeks already, can anyone knows what need to be corrected? Thank you so much!

New contributor

Юрий XXX is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật