我正在尝试制作Windows Form App。该应用程序使用多线程,每个线程调用一个方法,它更新在主线程上创建的控件。我使用invoke更新控件,应用程序适用于Windows服务器企业,但它在Windows 7 64位上运行。在WIndows 7上,应用程序在更新界面2次后停止执行任何操作。我不知道这似乎是什么问题。我试过多个线程和任务(Task.Factory.StartNew()
),我有相同的结果(更新控件2次)。没有错误消息。
谢谢。
修改
在CallMethod()
我正在呼叫WCF并等待响应。似乎WCF调用正在为前两个线程返回一些东西,而其余的则不是......
代码:
主要方法:
for (int i = 0; i < NoThreads; i++)
{
int index = i;
Thread t = new Thread(CallMethod);
t.Name = "Thread [" + Cicle + "] Cicle [" + i + "]";
threads[i] = t;
}
for (int i = 0; i < NoThreads; i++)
{
threads[i].Start();
}
CallMethod:
private string CallMethod()
{
try
{
//calling a webservice
string message = .....
if (txtResult.InvokeRequired)
{ txtResult.Invoke((MethodInvoker)(() => txtResult.AppendText(message))); }
catch
{throw;}
}
答案 0 :(得分:0)
对于调试,请确保通过CallMethod()的所有路径都更新UI(即使它只是带有“到此点”文本)。似乎txtResult.InvokeRequired可能是false,或者您可能正在从Web请求中获得异常。
答案 1 :(得分:0)
解决了问题 我必须在每个线程中调用WCF后关闭连接
答案 2 :(得分:-1)
在x64计算机(Windows 7)上处理线程的示例:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
private static string rootPath = "";
public Server()
{
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
this.tcpListener = new TcpListener(ipAddress, 9501);
//this.tcpListener = new TcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Endpoint1"].IPEndpoint);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
Trace.WriteLine("Server Working", "Information");
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
Trace.WriteLine("Server TcpListener Started", "Information");
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
Trace.WriteLine("Server TcpListener New Client", "Information");
// create a thread to handle the client
//ParameterizedThreadStart HandleClientConn;
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Trace.WriteLine("Server TcpListener New Client Handle Thread", "Information");
TcpClient tcpClient = (TcpClient)client;
NetworkStream nStream = tcpClient.GetStream();
Image img = Image.FromStream(nStream);
Trace.WriteLine("Server TcpListener Image is received", "Information");
string imageName = client.GetHashCode() + ".jpg";
string imagePath = Path.Combine(Environment.GetEnvironmentVariable("RoleRoot") + @"\", @"approot\"+ imageName);
img.Save(imagePath, ImageFormat.Jpeg);
rootPath = Environment.GetEnvironmentVariable("RoleRoot");
Dictionary<string, string> templates = GetTemplates();
string sDataDir = String.Format("{0}StasmData\\", rootPath);
StasmHelper stasm = new StasmHelper();
Face retVal = stasm.GetHumanFace(imagePath, sDataDir, templates);
File.Delete(imagePath);
}