September 18th, 2012, 12:30 AM
#1
[C#] Adding Event Listener to static void Main() fails, why?
Hi All,
Trying to download some strings from a webpage, then fires an event for each download that completes. However, when trying to add the event listener, the program throws the following error:
An object reference is required for the non-static field, method, or property 'Test.Program.client_OpenReadCompleted(object, System.Net.OpenReadCompletedEventArgs)'
Code is here: http://codepad.org/mAZVd4DJ
The line with the error is line 22.
How can I get around this?
Please let me know if you require more information, thanks!
September 18th, 2012, 05:00 PM
#2
Re: [C#] Adding Event Listener to static void Main() fails, why?
Just pull the work into a non-static method.
Code:
class Program
{
static void Main( string [ ] args )
{
var program = new Program();
program.ProcessConnections( );
}
public void ProcessConnections()
{
List<string> dataList = new List<string>( );
for ( int index = 0; index < 5; index++ )
{
try
{
WebClient client = new WebClient( );
client.OpenReadCompleted += Client_OpenReadCompleted;
Stream stream = client.OpenRead( new Uri( "http://graph.facebook.com/347971448616743/photos?limit=30&offset=" + index * 10 ) );
StreamReader streamReader = new StreamReader( stream );
dataList.Add( streamReader.ReadToEnd( ) );
}
catch ( WebException webException )
{
Console.WriteLine( webException.Message );
}
}
Console.WriteLine( "Finished downloading, showing results..." );
foreach ( string data in dataList )
{
Console.WriteLine( data.Substring( 0, 50 ) );
}
Console.ReadLine( );
}
public void Client_OpenReadCompleted( object sender, OpenReadCompletedEventArgs e )
{
Console.WriteLine( "Finished a download" ); }
}
September 18th, 2012, 05:25 PM
#3
Re: [C#] Adding Event Listener to static void Main() fails, why?
Perfect, thank you very much!
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width
Bookmarks