我正在编写服务器客户端,并希望使用Task.Run(() => {SomeCode});
运行操作
这是我的代码
Task.Run(() =>
{
_control_com_peer2peer.VerifyConnection(port: 6001, IpAddressClient: ComboBoxRemoteIP.Text);
});
内部代码基本上是
public void VerifyConnection(int port, string IpAddressClient)
{
Control_PeerSessionListCheckCreate(RemoteIP: IpAddressClient);
Domain_Peer2PeerCom.peerSessionList.Find(x => x.remoteIP == IpAddressClient).CommandLocker("Hello");
Domain_Peer2PeerCom.PeerSessionChangeIsConnected(IpAddressClient, true);
}
我在VerifyConnection
内打破了分数,并且没有一个被解雇。
修改
按钮触发任务的整个代码
private void Connect_Click(object sender, EventArgs e)
{
string s_RemoteIP;
if (ComboBoxRemoteIP.Text != "")
{
if (Network.startPing(ComboBoxRemoteIP.Text))
{
Control_Peer2peerCom.Control_PeerSessionListCheckCreate(ComboBoxRemoteIP.Text);
//bool IspeerReal = Control_Peer2peerCom.peerSessionListGet(ComboBoxRemoteIP.Text, out peerSessionCurrentParam);
if (/*IspeerReal&&*/!(Control_Peer2peerCom.Control_PeerSessionCheckIsConnected(ComboBoxRemoteIP.Text)))//peerSessionCurrentParam.IsConnetcted))//(!Peer2peerCom.isPeerConnetionVerifaied)
{
SelectiveEnable();
tbStatus.Text = "Wait...";
tbStatus.BackColor = Color.Yellow;
s_RemoteIP = ComboBoxRemoteIP.Text;
Task.Run(() =>
{
_control_com_peer2peer.VerifyConnection(port: 6001, IpAddressClient:
ComboBoxRemoteIP.Text);
});
//more code here , Not related
}
当然,如果我在Task.Run
运行方法运行正常
可能是什么原因
答案 0 :(得分:1)
问题出在task.run当然,一旦我改为简单线程异常抛出跨线程!我的错误是将ComboBoxRemoteIP.Text
发送给任务
任务没有任何异常,所以我希望能够解决问题
我修改它的方式只是添加
String Ipddress = ComboBoxRemoteIP.Text
并发送字符串