MSDN中使用回調方法檢索數據的案例
https://msdn.microsoft.com/zh-cn/library/ts553s52(v=vs.110).aspx
using System;
using System.Threading;
public class ThreadWithState
{
private string boilerplate;
private int value;
private ExampleCallback callback;
public ThreadWithState(string text, int number, ExampleCallback callback)
{
boilerplate = text;
value = number;
this.callback = callback;
}
public void ThreadProc()
{
Console.WriteLine(boilerplate, value);
if (callback != null)
callback(1);
}
}
public delegate void ExampleCallback(int lineCount);
public class Example
{
public static void Main()
{
ThreadWithState tws = new ThreadWithState( "This report displays the number {0}.",42, new ExampleCallback(ResultCallback) );
Thread t = new Thread(new ThreadStart(tws.ThreadProc));
t.Start();
Console.WriteLine("Main thread does some work, then waits.");
t.Join();
Console.WriteLine( "Independent task has completed; main thread ends.");
}
public static void ResultCallback(int lineCount)
{
Console.WriteLine( "Independent task printed {0} lines.", lineCount);
}
}
問題1:public delegate void ExampleCallback(int lineCount);這個語句,不在主程序中,也沒有包含在其他的類中,為什麼可以這樣寫?不是說“所有可執行的 C# 代碼都必須包含在類中”嗎?為什麼ExampleCallback在public class ThreadWithState{}類中是可見的?
問題2:如果 t.Start()很快就執行完了,那麼 t.Join()是否還會起作用?
問題1補充:為什麼ExampleCallback在public class ThreadWithState{}類中是可見的?