我创建了一个自定义自动完成控件,当用户按下一个键时,它会在另一个线程上查询数据库服务器(使用Remoting).当用户输入非常快时,程序必须取消先前执行的请求/线程.
我以前首先将它实现为AsyncCallback,但我发现它很麻烦,要遵循的房子规则太多(例如AsyncResult,AsyncState,EndInvoke)加上你必须检测BeginInvoke'd对象的线程,这样你就可以终止先前执行的线程了.此外,如果我继续AsyncCallback,那些AsyncCallbacks上没有可以正确终止先前执行线程的方法.
EndInvoke无法终止线程,它仍然会完成待终止线程的操作.我仍然会在线程上使用Abort().
所以我决定用纯线程方法实现它,没有AsyncCallback.这个thread.abort()是否正常且安全吗?
public delegate DataSet LookupValuesDelegate(LookupTextEventArgs e);
internal delegate void PassDataSet(DataSet ds);
public class AutoCompleteBox : UserControl
{
Thread _yarn = null;
[System.ComponentModel.Category("Data")]
public LookupValuesDelegate LookupValuesDelegate { set; get; }
void DataSetCallback(DataSet ds)
{
if (this.InvokeRequired)
this.Invoke(new PassDataSet(DataSetCallback), ds);
else
{
// implements the appending of text on textbox here
}
}
private void txt_TextChanged(object sender, EventArgs e)
{
if (_yarn != null) _yarn.Abort();
_yarn = new Thread(
new Mate
{
LookupValuesDelegate = this.LookupValuesDelegate,
LookupTextEventArgs =
new LookupTextEventArgs …Run Code Online (Sandbox Code Playgroud)