在C#中,我应该如何关闭正在运行的线程(Access DB)?

问题描述:

VS 2008/C#/MS Access 2003/2007

VS 2008 / C# / MS Access 2003 / 2007

我附上了代码片段,该片段在发布模式下引发异常.在调试模式下,应用程序运行良好.

I have attached Code Snippet which throws exception on Release Mode. In Debug Mode, Application works great.

为了测试这段代码,我转到了控制台应用程序.每当我运行该应用程序时,它都表明MS Access DB已经在使用中.

In order to test this piece of code, I moved to Console Application. When ever I run the application, it shows MS Access DB is already in Use.

因此,在执行这段代码之前,我需要终止MS Access DB Process.无论是否在使用中,我都需要杀死所有缓冲进程.

So, before executing this piece of code, I need to Kill MS Access DB Process. Whether it is in use or not, I need to kill all the buffer process.

在执行这段代码之前,我应该如何终止进程?

How should I kill the process before I execute this piece of code ?

try
    {

        Access.Application access1 = new Access.Application();

        // Open the Access database for exclusive access
        string sSalisburyAccessDB = Server.MapPath("~/App_Data/Salisbury.mdb");

        access1.OpenCurrentDatabase(sSalisburyAccessDB, true, null);

        // Drop the existing table data

        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "drug");
        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "patplan");
        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "plans");
        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "price");
        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "rx");
        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "patient");
        access1.DoCmd.DeleteObject(Access.AcObjectType.acTable, "plntrak");

        // Run the saved import
        access1.DoCmd.RunSavedImportExport("SalisburyODBC");

        // Close the database
        access1.CloseCurrentDatabase();

        // Quit MS Access
        access1.Quit(Access.AcQuitOption.acQuitSaveAll);

       Response.Write("successful");

    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }

我怀疑问题是,如果在主块中引发异常,则您不关闭连接.尝试放置access1.CloseCurrentDatabase();.在最后一块.

I suspect the issue is you dont close the connection if an exception is raised in the main block. Try putting the access1.CloseCurrentDatabase(); in a finally block.

编辑:如果您确实想终止该过程,则可以使用

EDIT If you really want to kill the process then you can use Process.Kill. I would recomend against it though as you could cause your users to lose data.