0

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,

2
  • You are right but, why do you need the delegate here, you could just call SaveData directly.
    – Jodrell
    Sep 5, 2013 at 9:05
  • hi its just a test for me to understanding the delegate, of course i can call function directly.
    – cyrus-d
    Sep 5, 2013 at 9:13

2 Answers 2

1

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.