Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Developing U++ » UppHub » Coroutines package for U++
Re: Coroutines package for U++ [message #59151 is a reply to message #59126] Wed, 09 November 2022 22:52 Go to previous messageGo to previous message
Oblivion is currently offline  Oblivion
Messages: 1094
Registered: August 2007
Senior Contributor
Hello,

As per Lance's request, I am adding some "non-trivial" coroutines examples to the package.
To demonstrate its usage, I have started with adapting the uppsrc/reference/GuiWebDownload example, so that it can be compared:

#include <CtrlLib/CtrlLib.h>
#include <CoRoutines/CoRoutines.h>


// GuiWebDownloader example, adapted to coroutines.

using namespace Upp;


CoRoutine<void> HttpDownload(const String& url)
{
	Progress pi;
	String path = AppendFileName(Nvl(GetDownloadFolder(), GetHomeDirFile("downloads")), GetFileName(url));
	HttpRequest http(url);
	http.Timeout(0);
	int loaded = 0;
	{
		FileOut out(path);
		http.WhenContent = [&out, &loaded](const void *ptr, int size) { out.Put(ptr, size); loaded += size; };
		while(http.Do()) {
			if(http.GetContentLength() >= 0) {
				pi.SetText("Downloading " + GetFileName(url));
				pi.Set((int)loaded, (int)http.GetContentLength());
			}
			else {
				pi.Set(0, 0);
				pi.SetText(http.GetPhaseName());
			}
			if(pi.Canceled())
				http.Abort();
			else
				co_await CoSuspend();
		}
	}
	if(http.IsFailure()) {
		DeleteFile(path);
		Exclamation("Download has failed.&\1" +
			(http.IsError()
				? http.GetErrorDesc()
					: AsString(http.GetStatusCode()) + ' ' + http.GetReasonPhrase()));
	}
}

GUI_APP_MAIN
{
	StdLogSetup(LOG_COUT|LOG_FILE);
	
	String url = "http://downloads.sourceforge.net/project/upp/upp/4179/upp-x11-src-4179.tar.gz";

	for(;;) {
		if(!EditText(url, "Download", "URL"))
			return;
		auto downloader = HttpDownload(url); // Multiple downloaders can be created/run at once.
		try
		{
			while(downloader.Do())
				Sleep(1); // Simulate work.
		}
		catch(const Exc& e)
		{
			
		}
		catch(...)
		{
			
		}
	}
}


Best regards,
Oblivion


[Updated on: Wed, 09 November 2022 22:56]

Report message to a moderator

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Possible enhancement on UppHub
Next Topic: Links in UppHub
Goto Forum:
  


Current Time: Tue Jun 11 18:51:10 CEST 2024

Total time taken to generate the page: 0.01515 seconds