我正在尝试制作我的第一个应用程序,其中我使用事件在两个线程之间进行通信。我不太了解与代表一起工作,所以我需要建议如何完成我的申请以及我的错误是什么(如果有的话)?
我使用两个类。1 类,其中有两个线程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
public class MyThreadTest : EventArgs
{
private string _threadOutput = "";
private bool _stopThreads = false;
/// <summary>
/// Thread 1: Loop continuously,
/// Thread 1: Displays that we are in thread 1
/// </summary>
void DisplayThread1()
{
while (_stopThreads == false)
{
Console.WriteLine("Display Thread 1");
// Assign the shared memory to a message about thread #1
_threadOutput = "Hello Thread1";
Thread.Sleep(1000); // simulate a lot of processing
// tell the user what thread we are in thread #1, and display shared memory
Console.WriteLine("Thread 1 Output --> {0}", _threadOutput);
}
}
/// <summary>
/// Thread 2: Loop continuously,
/// Thread 2: Displays that we are in thread 2
/// </summary>
void DisplayThread2()
{
while (_stopThreads == false)
{
Console.WriteLine("Display Thread 2");
// Assign the shared memory to a message about thread #2
_threadOutput = "Hello Thread2";
Thread.Sleep(1000); // simulate a lot of processing
// tell the user we are in thread #2
Console.WriteLine("Thread 2 Output --> {0}", _threadOutput);
}
}
void CreateThreads()
{
// construct two threads for our demonstration;
Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
Thread thread2 = new Thread(new ThreadStart(DisplayThread2));
// start them
thread1.Start();
thread2.Start();
}
public static void Main()
{
MyThreadTest StartMultiThreads = new MyThreadTest();
StartMultiThreads.CreateThreads();
}
}
我知道有一些额外的代码,但通常我的目标是模拟两个线程。
我尝试实现我的委托并最终使用自定义事件将消息从第一个线程发送到第二个线程的第二个类(至少这是我的最终目标):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Class1
{
public delegate void ShowMyMessage(object sender, EventArgs e);
public event ShowMyMessage ShowIt;
// Invoke the ShowIt event; called whenever I like it :)
protected virtual void OnShowIt(EventArgs e)
{
if (ShowIt != null)
ShowIt(this, e);
}
}
class EventListener
{
private Class1 msg;
public EventListener(Class1 msg)
{
Class1 Message = msg;
// Add "ListChanged" to the Changed event on "List".
Message.ShowIt += new ShowMyMessage(MessageShowIt);
}
// This will be called whenever the list changes.
private void ListChanged(object sender, EventArgs e)
{
Console.WriteLine("This is called when the event fires.");
}
}
我知道这不仅仅是一个愚蠢的错误,但我需要知道这是否是创建活动的方式以及我如何才能成功完成我的工作?