此代码应从网页获取一条信息。 我的问题是它没有显示出来,并且不知道为什么。
我想以某种方式让它等待文件完成而不在那个之外创建一个函数。
我想从更大的文件中修复的实际代码:
public static string GetNews() { WebBrowser page = new WebBrowser(); string data = null; page.Navigate(launcherScriptAddress); page.DocumentCompleted += delegate { data = page.Document.GetElementById("news").InnerText; // can't return `data` from here }; return data; // returns null because it doesn't wait for document to be completed }This code should take a piece of information from a webpage. My problem is that it doesn't show correnctly and don't know why.
I want to make it somehow to wait for document completion without creating a function outside that one.
The actual code that I want to fix from a larger file:
public static string GetNews() { WebBrowser page = new WebBrowser(); string data = null; page.Navigate(launcherScriptAddress); page.DocumentCompleted += delegate { data = page.Document.GetElementById("news").InnerText; // can't return `data` from here }; return data; // returns null because it doesn't wait for document to be completed }最满意答案
这不会像你尝试的那样工作。 您的函数在执行page.DocumentCompleted-delegate之前返回。
因此,您唯一能做的就是将回调传递给在您的委托中执行的GetNews函数。
同步< - >异步的旧问题。
此外,您应该交换语句.Navigate和.DocumentCompleted + =以确保“page”在开始加载任何内容之前设置了回调。
[编辑]为此,您需要创建一个委托并更改您的功能:
public delegate void NewsCallback( string dataReceived ); public static void GetNews( NewsCallback callback ) { WebBrowser page = new WebBrowser(); string data = null; page.Navigate(launcherScriptAddress); page.DocumentCompleted += delegate { data = page.Document.GetElementById("news").InnerText; callback( data ); }; }之后,您可能想以这种方式调用它:
void CallMyNews(){ GetNews( (dataReceived) => { DoSomeStuffWith(dataReceived); } ); }This won't work the way you try to do it. Your function returns way before the page.DocumentCompleted-delegate is being executed.
So the only thing you can do is pass a callback to your GetNews-function that gets executed within your delegate.
The old problem with sync <-> async.
Besides, you should swap the statements .Navigate and .DocumentCompleted += to make sure "page" has the callback set before it even starts to load anything.
[edit] To do that, you need to create a delegate and change your function:
public delegate void NewsCallback( string dataReceived ); public static void GetNews( NewsCallback callback ) { WebBrowser page = new WebBrowser(); string data = null; page.Navigate(launcherScriptAddress); page.DocumentCompleted += delegate { data = page.Document.GetElementById("news").InnerText; callback( data ); }; }After that, you may want to call it this way:
void CallMyNews(){ GetNews( (dataReceived) => { DoSomeStuffWith(dataReceived); } ); }
更多推荐
发布评论