0

I have a form. On button click, it should redirect to a dll wherein there are 2 classes.
Classxyz:
Has 2 threads.
Thread 1: should have the method that inserts a string into an array
Thread 2: should have the method that returns the first element from the array
Classarray:
The array is in a classarray.

My problem:
I am not able to understand if my threads are performing their tasks.

Class xyz:

        public void ToDo(string str)
       {
        ThreadObject firstThreadObject = new ThreadObject();
        firstThreadObject.str = str;


        Thread firstThread = new Thread(DoWorkpeek);
        firstThread.Start(firstThreadObject);


        ThreadObject secondThreadObject = new ThreadObject();

        secondThreadObject.str = str;
        Thread secondThread = new Thread(DoWorkenque);
        secondThread.Start(secondThreadObject);

        firstThread.Abort();
        secondThread.Abort();

    }

    public void DoWorkpeek(object parameter)
    {
        ThreadObject threadObject = parameter as ThreadObject;
        str1 = objq.queuepeek(threadObject.str);
        MessageBox.Show(str1);
    }
    public void DoWorkenque(object parameter)
    {
        ThreadObject threadObject = parameter as ThreadObject;
        objq.enqueue(threadObject.str);
    }

Is my code correct?

MessageBox.show(str1);

is not showing.

4

1 回答 1

2

首先,Join()线程,不要Abort()他们。

其次,您可以使用一个ParameterizedThreadStart对象来启动线程,如下所示:

Thread firstThread = new Thread(new ParameterizedThreadStart(DoWorkpeek));
firstThread.Start(str);

...

firstThread.Join();
secondThread.Join();

另外,确保两个线程都可以访问您的 objq 对象(例如是静态的)并在访问时锁定它,如下所示:

ThreadObject threadObject = parameter as ThreadObject;
lock(objq)
    str1 = objq.queuepeek(threadObject.str);
MessageBox.Show(str1);

此外,MessageBox.Show(str1)您可以使用System.Diagnostics.Debug.WriteLine(str1)并写入调试输出窗口,而不是使用。

于 2013-10-15T08:40:29.590 回答