【发布时间】:2011-04-22 08:44:00
【问题描述】:
我正在为在线游戏制作机器人。 它可以工作,但它是单线程应用程序。
我想让它成为多线程应用程序。 我知道后台工作人员的工作原理。
对于我的所有任务,我使用一个添加了 Cookie 支持的 WebClient。
我的例子需要打开一个页面,等待 10 分钟然后执行下一条指令。 我也希望能够随时停止机器人。
我是否必须将我的 WebClient 对象传递给后台工作人员才能使用? 更新表单控件的最佳方式是什么?
我有一个类具有我想在主窗体上显示的所有值。 我应该在属性更改时触发一些事件吗?如果是的话,你能举个例子吗?
更新:
这是我的特殊 WebClient:
using System;
using System.Net;
namespace Game_Bot
{
class WebClientEx : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public WebClientEx()
{
CookieContainer = new CookieContainer();
}
public void ClearCookies()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = CookieContainer;
}
return request;
}
}
}
这是更新 UI 的好方法吗?或者有没有更好的?
public void SetStatus(string status)
{
if (TransferLeftLabel.Dispatcher.Thread == Thread.CurrentThread)
{
TransferLeftLabel.Text = status;
}
else
{
TransferLeftLabel.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
(Action)(() => { SetStatus(string status); }));
}
}
【问题讨论】:
-
如果你想让多个线程工作,我建议你手动使用线程而不是
BackgroundWorker控件。 -
使用手动线程,您还可以发送您想要的任何状态更新(通过在主线程上调用委托并检查 InvokeRequired)。 Backgroundworker 仅支持向 UI 报告百分比。
标签: c# .net backgroundworker webclient bots