Problem with C # static scope

Using WPF and .NET 4.0.

I load some data using WebClientand using DownloadStringCompletedEventHandlerto disable the function DownloadCompletedCallbackafter completion.

The problem I am facing is that when DownloadCompletedCallbackI call, I try to set the contents of the label in the main form and present an error.

An object reference is required for a non-static field, method or property "Armory.MainWindow.lblDebug".

I understand that this is because the function is DownloadCompletedCallbackdeclared as static, but I do not understand why it matters.

Here is the code I'm using.

public static void DownloadHTML(string address)
{
    WebClient client = new WebClient();

    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadCompletedCallback);

    client.DownloadStringAsync(new Uri(address));
}

private static void DownloadCompletedCallback(Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        lblDebug.Content = (string)e.Result;
    }
}
+3
source share
5 answers

, , DownloadCompletedCallback - , , .

#:

, . . .

. , . , .

, , -, . , , , , , .

, :

Class Example{...}

var ExampleOne = new Example();
var ExampleTwo = new Example();

Example.CallStaticMethod();

, , ? ExampleOne ExampleTwo, . , , ( ). , . .. , .

+3

- . .. ; . .

, , 5 , , , , .

+2

, lblDebug. - ( static), , lblDebug.

lblDebug, , , , !

0
source

You cannot use lblDebug in a static method. Instead, you can change the DownloadHTML method to accept the callback:

public static void DownloadHTML(
     string address, 
     DownloadStringCompletedEventHandler callWhenCompleted)
{
    WebClient client = new WebClient();

    client.DownloadStringCompleted += 
        new DownloadStringCompletedEventHandler(callWhenCompleted);

    client.DownloadStringAsync(new Uri(address));
}

private void DownloadCompletedCallback(
    Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        lblDebug.Content = (string)e.Result;
    }
}

Using:

DownloadHTML(
     "http://stackoverflow.com/questions/5168788/c-static-scope-issue",
     this.DownloadCompletedCallback);
0
source

I think this is also because you cannot access lblDebug because it is in a different thread. (DownloadCompletedCallback isync, so it runs in a different thread). You need to call lblDebug with the dispatcher object from its parent. You will have to look for a challenge, but I do not have a visual studio here for the exact code.

0
source

Source: https://habr.com/ru/post/1795753/


All Articles