c# - 优雅地关闭多线程应用程序?

标签 c# database multithreading application-close

我有一个有两个线程的应用程序。

第一个(主线程)使用socket获取数据并更新DataTables

第二个将数据表插入数据库。

应用程序运行正常,但当它关闭时,主线程完成读取数据并在第二个线程中调用 Abort 方法,这可能会插入到数据库中,这会导致数据不一致。

目前我正在使用以下解决方案来克服“插入期间中止”

编辑: 在强大的答案之后我更改了代码

void MainThread()
{
     while(Read())
     {
        //Read Data through socket
        try
        {
           //Wait on Mutex1
           //Update Tables
        }
        finally
        {
          //Release Mutex1
        }
     }
   _isrunning = false;
   _secondThread.Join();
}
void SecondThread()
{
     while(_isrunning)
     {
        try
        {
           //Wait on Mutex1
           //Insert Tables into Database using transactions
        }
        finally
        {
           //Release Mutex1           
        }
     }
}

最佳答案

只要两个线程都没有被标记为后台线程,应用就会一直运行直到两个线程都退出。所以真的,你需要做的就是让每个线程分别干净地退出。对于写入数据库的线程,这可能意味着耗尽生产者/消费者队列并检查标志以退出。

我展示了一个合适的生产者/消费者队列here - worker 只是:

void WriterLoop() {
    SomeWorkItem item; // could be a `DataTable` or similar
    while(queue.TryDequeue(out item)) {
        // process item
    }
    // queue is empty and has been closed; all done, so exit...
}

这是一个基于 SizeQueue<> 的完整示例- 请注意,在读取器 完全退出之前,进程不会退出。如果您不想清空队列(即您希望更快退出,并忘记任何未决工作),那么很好 - 在某处添加一个额外的(易变的)标志。

static class Program {
    static void Write(object message) {
        Console.WriteLine(Thread.CurrentThread.Name + ": " + message);
    }
    static void Main() {
        Thread.CurrentThread.Name = "Reader";
        Thread writer = new Thread(WriterLoop);
        writer.Name = "Writer";
        var queue = new SizeQueue<int>(100);
        writer.Start(queue);
        // reader loop - note this can run parallel
        // to the writer
        for (int i = 0; i < 100; i++) {
            if (i % 10 == 9) Write(i);
            queue.Enqueue(i);
            Thread.Sleep(5); // pretend it takes time
        }
        queue.Close();
        Write("exiting");
    }
    static void WriterLoop(object state) {
        var queue = (SizeQueue<int>)state;
        int i;
        while (queue.TryDequeue(out i)) {
            if(i%10==9) Write(i);
            Thread.Sleep(10); // pretend it takes time
        }
        Write("exiting");
    }
}

关于c# - 优雅地关闭多线程应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1054611/

相关文章:

c# - OAuth v2.0 结合 ASP.NET MVC 4 Web API

c# - Eval函数是C#

mysql - 如果其他条目不为空,则不为空

c - OpenMP 中的插入排序

c++ - 标准 C++ 中的异步线程

c# - C# 代码背后的数据绑定(bind)

database - 将 Yii2 登录表单连接到数据库

sql-server - 将 NULL 值更改为 SQL Server 中的另一个值

python - Python 中的多线程 MD5 校验和

c# - Gridview 使用图像排序