我正在开发 ac# user-control @ work。该控件只是加载一些信息和数据并显示它。
现在我想为控件的用户提供一个选项来加载数据异步 .. smth 像这样:
Cntrl.LoadSmthAsync(..)
Cntrl.LoadSmthComplete //EventHandler to give feedback if the Load was successfull.
我决定使下载函数异步并通过 EventHandlers 提供返回值。
但是那个代码变得相当复杂......毕竟。
这里有一些代码来理解控件应该做什么:
public byte[] LoadByPos(int pos)
{
string url = Pos2Url(pos);
// update gui
this.textBox1.Text = url;
byte[] res = LoadByUrl(url);
// update gui
this.textBox2.Text = BytesToString(res);
return res;
}
public byte[] LoadByUrl(string url)
{
return Download(url);
}
//primary problem: download function
private byte[] Download(string url)
{
System.Threading.Thread.Sleep(1000 * 30);
return StringToBytes(url);
}
//secondary problem: an other function
private string Pos2Url(int pos)
{
System.Threading.Thread.Sleep(1000 * 5);
return pos.ToString();
}
// LoadByPosAsync
public delegate void LoadByPosDoneHandler(Object sender, byte[] e);
public event LoadByPosDoneHandler LoadByPosDone;
public void LoadByPosAsync(int pos)
{
string url = Pos2Url(pos);
// update gui
this.textBox1.Text = url;
LoadByUrlDone += new LoadByUrlDoneHandler(LoadByPosAsync_LoadByUrlDone);
LoadByUrlAsync(url);
}
public void LoadByPosAsync_LoadByUrlDone(object sender, byte[] e)
{
// update gui
this.textBox2.Text = BytesToString(e);
LoadByUrlDone = null;
LoadByPosDone(sender, e);
}
//LoadByUrlAsync
public delegate void LoadByUrlDoneHandler(Object sender, byte[] e);
public event LoadByUrlDoneHandler LoadByUrlDone;
public void LoadByUrlAsync(string url)
{
DownloadDone += new DownloadDoneHandler(LoadByUrlAsync_DownloadDone);
DownloadAsync(url);
}
private void LoadByUrlAsync_DownloadDone(object sender, byte[] e)
{
LoadByUrlDone(sender, e);
}
//DownloadAsync
private delegate void DownloadDoneHandler(Object sender, byte[] e);
private event DownloadDoneHandler DownloadDone;
private void DownloadAsync(string url)
{
BackgroundWorker bw_DownloadAsync = new BackgroundWorker();
bw_DownloadAsync.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_DownloadAsync_RunWorkerCompleted);
bw_DownloadAsync.DoWork += new DoWorkEventHandler(bw_DownloadAsync_DoWork);
bw_DownloadAsync.RunWorkerAsync(url);
}
void bw_DownloadAsync_DoWork(object sender, DoWorkEventArgs e)
{
byte[] res = Download((string)e.Argument);
e.Result = res;
}
void bw_DownloadAsync_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
DownloadDone(sender, (byte[])e.Result);
}
有没有更简单的方法来完成我打算做的事情?
提前谢谢