好吧,我又在为一些代码苦苦挣扎,但它不起作用。基本上,我有一个简单的 Student 类,其中包含姓名、姓氏和组号:
[XmlRoot]
public class Student
{
string name;
string surname;
int group;
public Student(string _name, string _surname, int _group)
{
name= _name;
surname= _surname;
group= _group;
}
public Student()
{
}
public void writeAttributes()
{
Console.WriteLine("{0}{1}{2}",name, surname, group);
}
}
然后,我在 Visual Studio 中的解决方案有两个项目:一个是发送方,另一个是接收方。我想要完成的是通过 MSMQ(异步)发送这个类的一个实例。这是发件人代码:
class Program
{
static MessageQueue mq;
static void SendMessage(object sender, EventArgs e)
{
System.Messaging.Message msg = new System.Messaging.Message();
try
{
msg.Label = "Message Label";
mq.Send(new Student("Name", "Surname", 1000));
Console.WriteLine("We send a Student");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main(string[] args)
{
Timer timer1 = new Timer();
if (MessageQueue.Exists(@".\private$\NewPrivateQ"))
mq = new MessageQueue(@".\private$\NewPrivateQ");
else
mq = MessageQueue.Create(@".\private$\NewPrivateQ");
mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(Student) });
//init the timer
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(SendMessage);
myTimer.Interval = 3000;
myTimer.Enabled = true;
while (true) ;
}
}
我使用计时器,每 3 秒发送一次信息。而且,这是接收器代码:
class Program
{
static void OnMessageArrival(IAsyncResult ar)
{
MessageQueue mq = (MessageQueue)ar.AsyncState;
try
{
Message msg = mq.EndReceive(ar);
var message = (Student)msg.Body;
//Console.WriteLine(message);
message.writeAttributes();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
mq.BeginReceive(TimeSpan.FromSeconds(5), mq,
new AsyncCallback(OnMessageArrival));
}
}
static void Main(string[] args)
{
MessageQueue mq = new MessageQueue(@".\private$\NewPrivateQ");
mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(Student) });
while (true)
{
try
{
IAsyncResult iar = mq.BeginReceive(TimeSpan.FromSeconds(5), mq, new AsyncCallback(OnMessageArrival));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
我什么都没有收到。我尝试了多种方法。我试图将 XmlFormatter 更改为 BinaryFormatter,但没有成功。
另一个有用的信息:Student 类,它包含在两个项目中:发送者和接收者。