Ave
Ave

Reputation: 4430

How to waiting thread completed in C#?

I create two thread to get a table and a function ExcelSave(DataTable, nameofSheetinExcel) to save all DataTable to Excel base on a name of Thread.

I want to wait for first thread save completed and go to the second thread to save.

I create two thread:

var t1 = new Thread(new ThreadStart(RegisterInfo))
{
    Name = "Thread1"
};
t1.Start();

var t2 = new Thread(new ThreadStart(RegisterInfo))
{
    Name = "Thread2"
};
t2.Start();
t1.Join();
t2.Join();

My code to save file excel like this:

if (Thread.CurrentThread.Name == "Thread1")
        ExcelSave(dt, "Thread 1");
else
        ExcelSave(dt, "Thread 2");

Because I have exception:

Error when saving file because the process cannot access the file 'D:\lapproject\bin\Debug\data.xlsx' because another process is using it. System.Exception {System.IO.IOException}`

Have any method to avoid this? Thanks for all people.

Upvotes: 0

Views: 53

Answers (1)

Nikhil.Patel
Nikhil.Patel

Reputation: 959

You can use following methods to prevent access the shared resource by a multiple thread at a same time and it will manage your error.

  1. Use mutex class to handle the code:

    private readonly Mutex m = new Mutex();
    public void ThreadSafeMethod() {
        m.WaitOne();
        try {
            /*excel related critical code */
        } finally {
            m.ReleaseMutex();
        }
    }
    
  1. use lock method:

    private readonly object syncLock = new object();
    
    public void ThreadSafeMethod() {
        lock(syncLock) {
            /*excel related critical code */
        }
    }
    

Upvotes: 1

Related Questions