带回调的线程示例不起作用。
我正在研究这个示例,但我无法将回调和线程连接起来。 我想要的是这个。
1) 按下按钮 2)启动进度条运行 3)调用一个新线程来执行一些长时间运行的进程 4) 对长时间运行的进程的回调应触发进度条停止。
下面我有一些东西...尽管 DoSomethingInThread 的回调参数为空。 StopProgressBar() 作用于 ProgressBar 控件,因此它不能是静态的。
static bool done;
static readonly object locker = new object();
static ParameterizedThreadStart threadStarter = new ParameterizedThreadStart(DoSomethingInThread);
private Thread workerThread = new Thread(threadStarter);
public delegate void StopProgressBarCallback()
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
StartProgressBar();
workerThread.Start();
}
static void DoSomethingInThread(object callback)
{
StopProgressBarCallback stopper = callback as StopProgressBarCallback;
lock (locker)
{
Thread.Sleep(5 * 1000);
}
stopper();
}
private void StartProgressBar()
{
progressBar1.MarqueeAnimationSpeed = 30;
progressBar1.Style = ProgressBarStyle.Marquee;
}
public void StopProgressBar()
{
progressBar1.Style = ProgressBarStyle.Continuous;
}
I am working on this example, but I am unable to mesh the callback and the threading.
What I want is this.
1) Press button
2) Start the progress bar running
3) Call to a new thread to perform some long running process
4) A callback on the long running process should trigger the progress bar to stop.
Below I have something...Although the callback parameter for DoSomethingInThread comes in as null.
The StopProgressBar() acts on the ProgressBar control, so it cannot be static.
static bool done;
static readonly object locker = new object();
static ParameterizedThreadStart threadStarter = new ParameterizedThreadStart(DoSomethingInThread);
private Thread workerThread = new Thread(threadStarter);
public delegate void StopProgressBarCallback()
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
StartProgressBar();
workerThread.Start();
}
static void DoSomethingInThread(object callback)
{
StopProgressBarCallback stopper = callback as StopProgressBarCallback;
lock (locker)
{
Thread.Sleep(5 * 1000);
}
stopper();
}
private void StartProgressBar()
{
progressBar1.MarqueeAnimationSpeed = 30;
progressBar1.Style = ProgressBarStyle.Marquee;
}
public void StopProgressBar()
{
progressBar1.Style = ProgressBarStyle.Continuous;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看 backgroundworker 类,它更多适合您想要做的事情,并且更容易掌握!
一般来说,您不应该“更新”Thread 实例。最好使用线程池,一个后台或者如果您使用 .net 4,则为 任务 对象来自线程并行库。
Have a look at the backgroundworker class, it is more suitable for what you are trying to do and a whole lot easier to get to grips with!
Generally, you shouldn't ever be 'newing' up Thread instances. It is better to use the thread pool, a background worker or if you're on .net 4, a task object from the thread parallel library.