多线程问题? !!! [英] problem in multithreading ? !!!

查看:78
本文介绍了多线程问题? !!!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void OnReceive(IAsyncResult ar)
 {

 clientSocket.EndReceive(ar);

//Convert the bytes received into an object of type Data
 Data msgReceived = new Data(byteData);

//Accordingly process the message received
 switch (msgReceived.cmdCommand)
 {

 case Command.openForm:

form1 f=new form1();
 the form is waiting here!!! \\\\\\ f.show();


break;

 }


//Start listening to receive more data from the user
 clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer,
 new AsyncCallback(OnReceive), null);

 }

推荐答案

除与其关联的UI线程外,请勿从该线程调用当前正在执行的UI对象的任何方法/属性.
相反,您需要使用System.Windows.Threading.DispatcherInvokeBeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms).

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview扫描仪和MD5的问题 [如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

此外,我不建议使用异步API,因为直接使用线程更直接,更简单,逻辑也更线性;您有了更多的控制权.当然,您将需要使用线程同步技术(越少越好,但是您需要确保代码是线程安全的).但是那些线程同步技术总是相同的,而异步代码则取决于特定的API.我认为当多线程不再是现在的普遍现象时,异步API就会兴旺起来.

—SA
You should never call any methods/properties of the currently executing UI objects from the thread other then its associated UI thread.

Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

Besides, I don''t recommend using asynchronous APIs, as direct use of threading is more straightforward, simple, the logic is more linear; you got more control. Of course, you will need to use thread synchronization techniques (the less, the better, but you need to make sure your code is thread safe). But those thread synchronization techniques are always the same, while asynchronous code depends on particular APIs. I think that asynchronous APIs flourished when multithreading was not a commonplace as it is now.

—SA


这篇关于多线程问题? !!!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆