1

单击按钮时,我正在尝试在 C# 中的服务器和客户端之间复制文件。我希望使用后台工作人员,因为我不希望副本在复制时使我的表单卡住。我有这个代码:

    private void connectBtn_Click(object sender, EventArgs e)
    {
         if (!isConnected)
         {
             clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             connectBtn.Text = "Disconnect From Server";
             connectBtn.Refresh();
             clientSock.Connect(remoteIpAddress, remotePort);
             statusColor.BackColor = Color.Green;
             statusColor.Refresh();
             isConnected = true;
             buttonAddDirectory.Enabled = true;
             buttonAddFile.Enabled = true;
             var bg = new BackgroundWorker();
             bg.DoWork += (sender, e) => copyDllsToServer();

             bg.RunWorkerAsync();
             if (backgroundWorker.IsBusy != true)
                 backgroundWorker.RunWorkerAsync();
         }
     }

复制函数是:copyDllsToServer()。

这样做时,我收到以下错误:A local variable named 'sender' cannot be declared in this scope because it would give a different meaning to 'sender', which is already used in a 'parent or current' scope to denote something else. 我该如何解决?

BackgroundWorker当多个客户端运行它时,它会正常工作吗?

4

1 回答 1

1

利用

bg.DoWork += (sender1, e) => copyDllsToServer(sender1, e);
                    ^_____________

代替

bg.DoWork += (sender, e) => copyDllsToServer();

或使用方法组作为

bg.DoWork += copyDllsToServer;

为什么不使用Socket类的异步方法?

该类Socket实现异步编程模型(APM)模式。检查以 .开头的套接字方法Begin/End

于 2013-02-03T11:57:15.977 回答