[001][Concurrency in C# CookBook]NotSupportedException能catch到不支援非同步執行的作業系統的錯誤

  • 9971
  • 0
  • 2015-11-23

摘要:[001][Concurrency in C# CookBook]NotSupportedException能catch到不支援非同步執行的作業系統的錯誤

NotSupportedException在Concurrency書中,作者有介紹到其功用為:能catch到不支援非同步執行的作業系統的錯誤。

擔心一些比較舊的某些版本的作業系統不支援非同步執行的話,就用NotSupportedException去catch。

在本人的電腦是支援的,因此...也測不到NotSupportedException的功用, 哈哈 XD

程式碼:

.aspx


<asp:Button ID="btnNotSupportedException" runat="server" Text="NotSupportedExceptionCatchNotSupportedOS" OnClick="btnNotSupportedException_Click" />

.aspx.cs


protected async void btnNotSupportedException_Click(object sender, EventArgs e)
{
	long longSum = 0;
	longSum = await TrySomethingAsync();            
	Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('sum=" + longSum.ToString() + "');", true);
}

private async Task TrySomethingAsync()
{
	long longSum = 0;
	try
	{
		longSum = await PossibleExceptionAsync();
	}
	catch (System.NotSupportedException ex)
	{
		//目前的作業系統win 8是支援await非同步處理的,所以...不會進來這個exception... @@"
		string strErrMsg = ex.ToString();
		return 0;
	}
	catch( Exception ex)
	{
		//只會進來這個exception...自己新增一般exception進來這邊自high一下 XD
		string strErrMsg = ex.ToString();
		return 0;
	}
	return longSum;
}

private async Task PossibleExceptionAsync()
{
	long longSum = 0;
	long longZero = 0;
	await Task.Run(() => { longSum = 1 / longZero; });            

	return longSum;
}

參考書籍:

Concurrency in C# CookBook

http://stephencleary.com/book/