Vahid Akbari
Vahid Akbari

Reputation: 189

Thread Exception handling

I have a function in my logical Layer that insert information by another thread and I want if unknown exception happen in that thread throw it but the problem is that in my application UnhandledExceptionEventHandler that get general exception it gives this error and i also don't want to shutdown the application:

The calling thread must be STA, because many UI components require this

///////////////////// this is my function in logical layer //////////
public string MahaleInsert(Mahales Mahale)
{
    Thread t = new Thread(delegate()
    {
        try
        {
            Mahale.OutMessage = DA_Agency.MahaleInsertDB(Mahale);
            Mahale.OutMessage = "SuccessInsert";
        }
        catch (Exception ex)
        {
            if (ex.Message.ToLower().Contains("violation of unique key constraint"))
                Mahale.OutMessage = "MahaleInsUniqueError";
            else
                throw;
        }
    });
    t.Start();
    t.Join();
    return Mahale.OutMessage;    
}

//////////////////////////// this in my aplication level  //////////////////
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    try
    {
        string messsage = GeneralMethod.CatchException(e.ExceptionObject as Exception);
        MessageClass.MessageBox(messsage);
    }
    catch
    {


    }
}

Upvotes: 0

Views: 129

Answers (1)

Amer Sawan
Amer Sawan

Reputation: 2292

Try To do the following :

    public string MahaleInsert(Mahales Mahale)
    {
        Thread t = new Thread(new ThreadStart(ThreadBody));
        t.Start();
        t.Join();
        return Mahale.OutMessage;
    }
    [STAThread]
    void ThreadBody()
    {
        try
        {
            Mahale.OutMessage = DA_Agency.MahaleInsertDB(Mahale);
            Mahale.OutMessage = "SuccessInsert";
        }
        catch (Exception ex)
        {
            if (ex.Message.ToLower().Contains("violation of unique key constraint"))
                Mahale.OutMessage = "MahaleInsUniqueError";
            else
                throw;
        }
    }

    //////////////////////////// this in my aplication level  //////////////////
    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        try
        {
            string messsage = GeneralMethod.CatchException(e.ExceptionObject as Exception);
            MessageClass.MessageBox(messsage);
        }
        catch
        {


        }
    }

Upvotes: 1

Related Questions