且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在Windows窗体应用程序中创建异步函数吗?

更新时间:2023-12-06 14:00:34

是的,有很多方法可以做到这一点。您正在寻找的短语是线程。



最简单的入门方法是使用BackgroundWorker对象:



Yes, and there are many ways of doing it. The phrase you're looking for is Threading.

The easiest way to get started is to user a BackgroundWorker object:

string filesToUpload_etc = "files";

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork+= delegate(object sender, DoWorkEventArgs args)
{
    foreach (string s in filesToUpload_etc.Split(''))
    {
        //do your thing
    }
};
worker.RunWorkerCompleted+= delegate(object sender, RunWorkerCompletedEventArgs args)
{
    //make something go "ping - done"
};

worker.RunWorkerAsync();







这很容易实现。



如果您希望从另一个线程到运行表单的主线程的进度报告,则会出现更多复杂情况。例如,有多个线程试图访问相同的变量,危险在于。



有几种方法可以解决几乎所有这些问题(我在看着你,Thread.Abort> _<<)。我不会详细说明,因为我不知道你需要多详细。只需发布一个新问题来解决这些复杂问题



祝你好运:)




This is dead easy to implement.

There are more complications if you want a progress report from another thread to the main thread that runs your forms. Dangers lie in have multiple threads trying to access the same variable, for example.

There are ways to get around almost all of these issues (I'm looking at you, Thread.Abort >_<<). I won't go into detail as I don't know how detailed you need. Just post a new question to address any of these complexities

Good luck :)