线程交互
C# form 窗体
我使用了一个线程来执行上传, 我要把 上传的进度 显示在 form 窗体的label中
我直接在线程里面写 label.text = persent 赋值 报"线程间操作无效"
也用了事件 ,还是报错
这个应该怎么实现 谢谢
[解决办法]
说错了哈,是公共变量,而且Control.CheckForIllegalCrossThreadCalls = false;在某些控件跨线程调用的时候会出错,所以你最好使用其他的更安全的方法,.net2.0有个东西叫backgroundwork,可以帮你实现简单的异步操作和消息传递
[解决办法]
- C# code
using System;
using System.Threading;
namespace Cmpxx
{
public delegate void ExampleCallback(int lineCount);
public class ThreadArgState
{
private string boilerplate = "";
private int value = 0;
private event ExampleCallback callback = null;
public ThreadArgState(string text, int number,ExampleCallback callbackDelegate)
{
boilerplate = text;
value = number;
callback = callbackDelegate;
}
public void ThreadProc()
{
Console.WriteLine(boilerplate, value);
Thread.Sleep(5000);
if (callback != null)
{
//触发事件
callback(20);
}
}
}
public class Example
{
public static void SCMain()
{
//主函数执行
ThreadArgState tws = new ThreadArgState("This report displays the number {0}.", 422, new ExampleCallback(ResultCallback));
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.WriteLine("Main thread does some work, then waits.");
t.Join(); //等待线程处理完毕后才执行后面的程序,把他注释掉在看运行结果就明白了
Console.WriteLine("Independent task has completed; main thread ends.");
}
public static void ResultCallback(int lineCount)
{
Console.WriteLine("Independent task printed {0} lines.", lineCount);
}
}
}