搜索两次会使Object引用为null

时间:2014-02-23 08:32:48

标签: vb.net api search nullreferenceexception google-search-api

“Button1的

Dim ex1 As New Threading.Thread(AddressOf ex1_sub)

Dim ex2 As New Threading.Thread(AddressOf ex2_sub)

ex1.Start()
ex2.Start()

'结束子

Sub ex1_sub()

Dim result_ex1 As IWebResult

Dim client_ex1 As New GwebSearchClient("http://www.google.com")

Dim results_ex1 As IList(Of IWebResult) = client_ex1.Search("love", 2)

For Each result_ex1 In results_ex1
MsgBox(result_ex1.Title)
Next

End Sub


Sub ex2_sub()
Dim result_ex2 As IWebResult

Dim client_ex2 As New GwebSearchClient("http://www.google.com")

Dim results_ex2 As IList(Of IWebResult) = client_ex2.Search("hate", 2)

For Each result_ex2 In results_ex2
MsgBox(result_ex2.Title)
Next

End Sub

它指向results_ex2或results_ex1并告诉我 对象引用未设置为对象的实例。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

如果您无法保证client_ex1.Search()client_ex2.Search()始终返回值,请在函数调用后进行简单检查以避免Null reference error。例如:

.......
Dim results_ex2 As IList(Of IWebResult) = client_ex2.Search("hate", 2)
If results_ex2 Is Nothing Then
    Console.WriteLine("API returns no result")
Else
    For Each result_ex2 In results_ex2
        MsgBox(result_ex2.Title)
    Next
End If
.......