cyrus-d
cyrus-d

Reputation: 843

Delegate in multithread application

I am new into delegate and I would like to see if the following code will cause any problem. The code I have written is not using shared variables but used a shared delegate as follow

       public delegate void delSaveData(string data1, string data2);
    private static delSaveData _delSaveData;
    static void Main(string[] args)
    {
        Thread td1 = new Thread(td1func);
        Thread td2 = new Thread(td2func);
        td1.Start();
        td2.Start();

    }
    private static void td1func()
    {
        while(true)
        {
            // do some operation
            _delSaveData= new delSaveData(SaveData);
            _delSaveData("someValueFromtd1", "someValueFromtd1");
        }
    }
    private static void td2func()
    {
        while(true)
        {
            // do some operation
            _delSaveData= new delSaveData(SaveData);
            _delSaveData("someValueFromtd2", "someValueFromtd2");
        }
    }
    private static void SaveData(string test1, string test2)
    {
        //Save Data in database
    }

I am assuming the code should work fine, because a new instance of the delegate will be create each time. Am I right? How about if something goes wrong in one of the created instance of delegate, is it going to affect other instance?

Thanks in advance for your answer,

Upvotes: 0

Views: 92

Answers (2)

Drew R
Drew R

Reputation: 3088

I am assuming the code should work fine, because a new instance of the delegate will be create each time. Am I right?

Have you tried to run the code a.k.a what have you tried? I don't see an immediate problem with it.

I can tell you that: If an exception (the problem that can occur when instancing a delegate, or executing it) is thrown from either thread it will go unhandled. An exception in one thread will not affect the other thread. So no, if "something goes wrong" it will not affect the other instance.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

First of all you're not modifying(adding or removing ) handlers to delegate. So why to create new all the time?

Try the following

private static readonly delSaveData _delSaveData = new delSaveData(SaveData);

This should be fine. you can use it in any number of threads.

How about if something goes wrong?

What goes wrong? not sure what you mean here.

Upvotes: 1

Related Questions