深入分析C# Task
Task的MSDN的描述如下:
【Task類的表示單個(gè)操作不會(huì)返回一個(gè)值,通常以異步方式執(zhí)行。
Task對(duì)象是一種的中心思想基于任務(wù)的異步模式首次引入.NETFramework 4 中。
因?yàn)橛蓤?zhí)行工作Task對(duì)象通常以異步方式執(zhí)行線程池線程上而不是以同步方式在主應(yīng)用程序線程中,可以使用Status屬性,并將IsCanceled, IsCompleted,和IsFaulted屬性,以確定任務(wù)的狀態(tài)。
大多數(shù)情況下,lambda 表達(dá)式用于指定該任務(wù)所執(zhí)行的工作量。
對(duì)于返回值的操作,您使用Task類?!?/p>
1、Task的優(yōu)勢(shì)
ThreadPool相比Thread來(lái)說(shuō)具備了很多優(yōu)勢(shì),但是ThreadPool卻又存在一些使用上的不方便。比如:
- ThreadPool不支持線程的取消、完成、失敗通知等交互性操作;
- ThreadPool不支持線程執(zhí)行的先后次序;
以往,如果開發(fā)者要實(shí)現(xiàn)上述功能,需要完成很多額外的工作,現(xiàn)在,F(xiàn)CL中提供了一個(gè)功能更強(qiáng)大的概念:Task。Task在線程池的基礎(chǔ)上進(jìn)行了優(yōu)化,并提供了更多的API。在FCL4.0中,如果我們要編寫多線程程序,Task顯然已經(jīng)優(yōu)于傳統(tǒng)的方式。
以下是一個(gè)簡(jiǎn)單的任務(wù)示例:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Task t = new Task(() =>
{
Console.WriteLine("任務(wù)開始工作……");
//模擬工作過(guò)程
Thread.Sleep(5000);
});
t.Start();
t.ContinueWith((task) =>
{
Console.WriteLine("任務(wù)完成,完成時(shí)候的狀態(tài)為:");
Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);
});
Console.ReadKey();
}
}
}
2、Task的用法
2.1、創(chuàng)建任務(wù)
?。ㄒ唬o(wú)返回值的方式
方式1:
var t1 = new Task(() => TaskMethod("Task 1"));
t1.Start();
Task.WaitAll(t1);//等待所有任務(wù)結(jié)束
注:任務(wù)的狀態(tài):
Start之前為:Created
Start之后為:WaitingToRun
方式2:
Task.Run(() => TaskMethod("Task 2"));
方式3:
Task.Factory.StartNew(() => TaskMethod("Task 3")); 直接異步的方法
//或者
var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));
Task.WaitAll(t3);//等待所有任務(wù)結(jié)束
//任務(wù)的狀態(tài):
Start之前為:Running
Start之后為:Running
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var t1 = new Task(() => TaskMethod("Task 1"));
var t2 = new Task(() => TaskMethod("Task 2"));
t2.Start();
t1.Start();
Task.WaitAll(t1, t2);
Task.Run(() => TaskMethod("Task 3"));
Task.Factory.StartNew(() => TaskMethod("Task 4"));
//標(biāo)記為長(zhǎng)時(shí)間運(yùn)行任務(wù),則任務(wù)不會(huì)使用線程池,而在單獨(dú)的線程中運(yùn)行。
Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);
#region 常規(guī)的使用方式
Console.WriteLine("主線程執(zhí)行業(yè)務(wù)處理.");
//創(chuàng)建任務(wù)
Task task = new Task(() =>
{
Console.WriteLine("使用System.Threading.Tasks.Task執(zhí)行異步操作.");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
});
//啟動(dòng)任務(wù),并安排到當(dāng)前任務(wù)隊(duì)列線程中執(zhí)行任務(wù)(System.Threading.Tasks.TaskScheduler)
task.Start();
Console.WriteLine("主線程執(zhí)行其他處理");
task.Wait();
#endregion
Thread.Sleep(TimeSpan.FromSeconds(1));
Console.ReadLine();
}
static void TaskMethod(string name)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
}
}
}
async/await的實(shí)現(xiàn)方式:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
async static void AsyncFunction()
{
await Task.Delay(1);
Console.WriteLine("使用System.Threading.Tasks.Task執(zhí)行異步操作.");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(string.Format("AsyncFunction:i={0}", i));
}
}
public static void Main()
{
Console.WriteLine("主線程執(zhí)行業(yè)務(wù)處理.");
AsyncFunction();
Console.WriteLine("主線程執(zhí)行其他處理");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(string.Format("Main:i={0}", i));
}
Console.ReadLine();
}
}
}
?。ǘХ祷刂档姆绞?/p>
方式4:
Task<int> task = CreateTask("Task 1");
task.Start();
int result = task.Result;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static Task<int> CreateTask(string name)
{
return new Task<int>(() => TaskMethod(name));
}
static void Main(string[] args)
{
TaskMethod("Main Thread Task");
Task<int> task = CreateTask("Task 1");
task.Start();
int result = task.Result;
Console.WriteLine("Task 1 Result is: {0}", result);
task = CreateTask("Task 2");
//該任務(wù)會(huì)運(yùn)行在主線程中
task.RunSynchronously();
result = task.Result;
Console.WriteLine("Task 2 Result is: {0}", result);
task = CreateTask("Task 3");
Console.WriteLine(task.Status);
task.Start();
while (!task.IsCompleted)
{
Console.WriteLine(task.Status);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
Console.WriteLine(task.Status);
result = task.Result;
Console.WriteLine("Task 3 Result is: {0}", result);
#region 常規(guī)使用方式
//創(chuàng)建任務(wù)
Task<int> getsumtask = new Task<int>(() => Getsum());
//啟動(dòng)任務(wù),并安排到當(dāng)前任務(wù)隊(duì)列線程中執(zhí)行任務(wù)(System.Threading.Tasks.TaskScheduler)
getsumtask.Start();
Console.WriteLine("主線程執(zhí)行其他處理");
//等待任務(wù)的完成執(zhí)行過(guò)程。
getsumtask.Wait();
//獲得任務(wù)的執(zhí)行結(jié)果
Console.WriteLine("任務(wù)執(zhí)行結(jié)果:{0}", getsumtask.Result.ToString());
#endregion
}
static int TaskMethod(string name)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
return 42;
}
static int Getsum()
{
int sum = 0;
Console.WriteLine("使用Task執(zhí)行異步操作.");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
}
}
}
async/await的實(shí)現(xiàn):
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
var ret1 = AsyncGetsum();
Console.WriteLine("主線程執(zhí)行其他處理");
for (int i = 1; i <= 3; i++)
Console.WriteLine("Call Main()");
int result = ret1.Result; //阻塞主線程
Console.WriteLine("任務(wù)執(zhí)行結(jié)果:{0}", result);
}
async static Task<int> AsyncGetsum()
{
await Task.Delay(1);
int sum = 0;
Console.WriteLine("使用Task執(zhí)行異步操作.");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
}
}
}
2.2、組合任務(wù).ContinueWith
簡(jiǎn)單Demo:
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
//創(chuàng)建一個(gè)任務(wù)
Task<int> task = new Task<int>(() =>
{
int sum = 0;
Console.WriteLine("使用Task執(zhí)行異步操作.");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
});
//啟動(dòng)任務(wù),并安排到當(dāng)前任務(wù)隊(duì)列線程中執(zhí)行任務(wù)(System.Threading.Tasks.TaskScheduler)
task.Start();
Console.WriteLine("主線程執(zhí)行其他處理");
//任務(wù)完成時(shí)執(zhí)行處理。
Task cwt = task.ContinueWith(t =>
{
Console.WriteLine("任務(wù)完成后的執(zhí)行結(jié)果:{0}", t.Result.ToString());
});
task.Wait();
cwt.Wait();
}
}
}
任務(wù)的串行:
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
//t1先串行
var t1 = Task.Factory.StartNew(() =>
{
stack.Push(1);
stack.Push(2);
});
//t2,t3并行執(zhí)行
var t2 = t1.ContinueWith(t =>
{
int result;
stack.TryPop(out result);
Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
});
//t2,t3并行執(zhí)行
var t3 = t1.ContinueWith(t =>
{
int result;
stack.TryPop(out result);
Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
});
//等待t2和t3執(zhí)行完
Task.WaitAll(t2, t3);
//t7串行執(zhí)行
var t4 = Task.Factory.StartNew(() =>
{
Console.WriteLine("當(dāng)前集合元素個(gè)數(shù):{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);
});
t4.Wait();
}
}
}
子任務(wù):
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
Task<string[]> parent = new Task<string[]>(state =>
{
Console.WriteLine(state);
string[] result = new string[2];
//創(chuàng)建并啟動(dòng)子任務(wù)
new Task(() => { result[0] = "我是子任務(wù)1。"; }, TaskCreationOptions.AttachedToParent).Start();
new Task(() => { result[1] = "我是子任務(wù)2。"; }, TaskCreationOptions.AttachedToParent).Start();
return result;
}, "我是父任務(wù),并在我的處理過(guò)程中創(chuàng)建多個(gè)子任務(wù),所有子任務(wù)完成以后我才會(huì)結(jié)束執(zhí)行。");
//任務(wù)處理完成后執(zhí)行的操作
parent.ContinueWith(t =>
{
Array.ForEach(t.Result, r => Console.WriteLine(r));
});
//啟動(dòng)父任務(wù)
parent.Start();
//等待任務(wù)結(jié)束 Wait只能等待父線程結(jié)束,沒辦法等到父線程的ContinueWith結(jié)束
//parent.Wait();
Console.ReadLine();
}
}
}
動(dòng)態(tài)并行(TaskCreationOptions.AttachedToParent) 父任務(wù)等待所有子任務(wù)完成后 整個(gè)任務(wù)才算完成
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public string Text { get; set; }
}
class Program
{
static Node GetNode()
{
Node root = new Node
{
Left = new Node
{
Left = new Node
{
Text = "L-L"
},
Right = new Node
{
Text = "L-R"
},
Text = "L"
},
Right = new Node
{
Left = new Node
{
Text = "R-L"
},
Right = new Node
{
Text = "R-R"
},
Text = "R"
},
Text = "Root"
};
return root;
}
static void Main(string[] args)
{
Node root = GetNode();
DisplayTree(root);
}
static void DisplayTree(Node root)
{
var task = Task.Factory.StartNew(() => DisplayNode(root),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
task.Wait();
}
static void DisplayNode(Node current)
{
if (current.Left != null)
Task.Factory.StartNew(() => DisplayNode(current.Left),
CancellationToken.None,
TaskCreationOptions.AttachedToParent,
TaskScheduler.Default);
if (current.Right != null)
Task.Factory.StartNew(() => DisplayNode(current.Right),
CancellationToken.None,
TaskCreationOptions.AttachedToParent,
TaskScheduler.Default);
Console.WriteLine("當(dāng)前節(jié)點(diǎn)的值為{0};處理的ThreadId={1}", current.Text, Thread.CurrentThread.ManagedThreadId);
}
}
}
2.3、取消任務(wù) CancellationTokenSource
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private static int TaskMethod(string name, int seconds, CancellationToken token)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
for (int i = 0; i < seconds; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(1));
if (token.IsCancellationRequested) return -1;
}
return 42 * seconds;
}
private static void Main(string[] args)
{
var cts = new CancellationTokenSource();
var longTask = new Task<int>(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);
Console.WriteLine(longTask.Status);
cts.Cancel();
Console.WriteLine(longTask.Status);
Console.WriteLine("First task has been cancelled before execution");
cts = new CancellationTokenSource();
longTask = new Task<int>(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);
longTask.Start();
for (int i = 0; i < 5; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
Console.WriteLine(longTask.Status);
}
cts.Cancel();
for (int i = 0; i < 5; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
Console.WriteLine(longTask.Status);
}
Console.WriteLine("A task has been completed with result {0}.", longTask.Result);
}
}
}
2.4、處理任務(wù)中的異常
單個(gè)任務(wù):
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static int TaskMethod(string name, int seconds)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
throw new Exception("Boom!");
return 42 * seconds;
}
static void Main(string[] args)
{
try
{
Task<int> task = Task.Run(() => TaskMethod("Task 2", 2));
int result = task.GetAwaiter().GetResult();
Console.WriteLine("Result: {0}", result);
}
catch (Exception ex)
{
Console.WriteLine("Task 2 Exception caught: {0}", ex.Message);
}
Console.WriteLine("----------------------------------------------");
Console.WriteLine();
}
}
}
多個(gè)任務(wù):
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static int TaskMethod(string name, int seconds)
{
Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",
name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
throw new Exception(string.Format("Task {0} Boom!", name));
return 42 * seconds;
}
public static void Main(string[] args)
{
try
{
var t1 = new Task<int>(() => TaskMethod("Task 3", 3));
var t2 = new Task<int>(() => TaskMethod("Task 4", 2));
var complexTask = Task.WhenAll(t1, t2);
var exceptionHandler = complexTask.ContinueWith(t =>
Console.WriteLine("Result: {0}", t.Result),
TaskContinuationOptions.OnlyOnFaulted
);
t1.Start();
t2.Start();
Task.WaitAll(t1, t2);
}
catch (AggregateException ex)
{
ex.Handle(exception =>
{
Console.WriteLine(exception.Message);
return true;
});
}
}
}
}
async/await的方式:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task ThrowNotImplementedExceptionAsync()
{
throw new NotImplementedException();
}
static async Task ThrowInvalidOperationExceptionAsync()
{
throw new InvalidOperationException();
}
static async Task Normal()
{
await Fun();
}
static Task Fun()
{
return Task.Run(() =>
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("i={0}", i);
Thread.Sleep(200);
}
});
}
static async Task ObserveOneExceptionAsync()
{
var task1 = ThrowNotImplementedExceptionAsync();
var task2 = ThrowInvalidOperationExceptionAsync();
var task3 = Normal();
try
{
//異步的方式
Task allTasks = Task.WhenAll(task1, task2, task3);
await allTasks;
//同步的方式
//Task.WaitAll(task1, task2, task3);
}
catch (NotImplementedException ex)
{
Console.WriteLine("task1 任務(wù)報(bào)錯(cuò)!");
}
catch (InvalidOperationException ex)
{
Console.WriteLine("task2 任務(wù)報(bào)錯(cuò)!");
}
catch (Exception ex)
{
Console.WriteLine("任務(wù)報(bào)錯(cuò)!");
}
}
public static void Main()
{
Task task = ObserveOneExceptionAsync();
Console.WriteLine("主線程繼續(xù)運(yùn)行........");
task.Wait();
}
}
}
2.5、Task.FromResult的應(yīng)用
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static IDictionary<string, string> cache = new Dictionary<string, string>()
{
{"0001","A"},
{"0002","B"},
{"0003","C"},
{"0004","D"},
{"0005","E"},
{"0006","F"},
};
public static void Main()
{
Task<string> task = GetValueFromCache("0006");
Console.WriteLine("主程序繼續(xù)執(zhí)行。。。。");
string result = task.Result;
Console.WriteLine("result={0}", result);
}
private static Task<string> GetValueFromCache(string key)
{
Console.WriteLine("GetValueFromCache開始執(zhí)行。。。。");
string result = string.Empty;
//Task.Delay(5000);
Thread.Sleep(5000);
Console.WriteLine("GetValueFromCache繼續(xù)執(zhí)行。。。。");
if (cache.TryGetValue(key, out result))
{
return Task.FromResult(result);
}
return Task.FromResult("");
}
}
}
2.6、使用IProgress實(shí)現(xiàn)異步編程的進(jìn)程通知
IProgress<in T>只提供了一個(gè)方法void Report(T value),通過(guò)Report方法把一個(gè)T類型的值報(bào)告給IProgress,然后IProgress<in T>的實(shí)現(xiàn)類Progress<in T>的構(gòu)造函數(shù)接收類型為Action<T>的形參,通過(guò)這個(gè)委托讓進(jìn)度顯示在UI界面中。
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void DoProcessing(IProgress<int> progress)
{
for (int i = 0; i <= 100; ++i)
{
Thread.Sleep(100);
if (progress != null)
{
progress.Report(i);
}
}
}
static async Task Display()
{
//當(dāng)前線程
var progress = new Progress<int>(percent =>
{
Console.Clear();
Console.Write("{0}%", percent);
});
//線程池線程
await Task.Run(() => DoProcessing(progress));
Console.WriteLine("");
Console.WriteLine("結(jié)束");
}
public static void Main()
{
Task task = Display();
task.Wait();
}
}
}
2.7、Factory.FromAsync的應(yīng)用 (簡(jiǎn)APM模式(委托)轉(zhuǎn)換為任務(wù))(BeginXXX和EndXXX)
帶回調(diào)方式的
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private delegate string AsynchronousTask(string threadName);
private static string Test(string threadName)
{
Console.WriteLine("Starting...");
Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
Thread.CurrentThread.Name = threadName;
return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
}
private static void Callback(IAsyncResult ar)
{
Console.WriteLine("Starting a callback...");
Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState);
Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
}
//執(zhí)行的流程是 先執(zhí)行Test--->Callback--->task.ContinueWith
static void Main(string[] args)
{
AsynchronousTask d = Test;
Console.WriteLine("Option 1");
Task<string> task = Task<string>.Factory.FromAsync(
d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke);
task.ContinueWith(t => Console.WriteLine("Callback is finished, now running a continuation! Result: {0}",
t.Result));
while (!task.IsCompleted)
{
Console.WriteLine(task.Status);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
Console.WriteLine(task.Status);
}
}
}
不帶回調(diào)方式的
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
private delegate string AsynchronousTask(string threadName);
private static string Test(string threadName)
{
Console.WriteLine("Starting...");
Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
Thread.CurrentThread.Name = threadName;
return string.Format("Thread name: {0}", Thread.CurrentThread.Name);
}
//執(zhí)行的流程是 先執(zhí)行Test--->task.ContinueWith
static void Main(string[] args)
{
AsynchronousTask d = Test;
Task<string> task = Task<string>.Factory.FromAsync(
d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call");
task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}",
t.Result));
while (!task.IsCompleted)
{
Console.WriteLine(task.Status);
Thread.Sleep(TimeSpan.FromSeconds(0.5));
}
Console.WriteLine(task.Status);
}
}
}
//Task啟動(dòng)帶參數(shù)和返回值的函數(shù)任務(wù)
//下面的例子test2 是個(gè)帶參數(shù)和返回值的函數(shù)。
private int test2(object i)
{
this.Invoke(new Action(() =>
{
pictureBox1.Visible = true;
}));
System.Threading.Thread.Sleep(3000);
MessageBox.Show("hello:" + i);
this.Invoke(new Action(() =>
{
pictureBox1.Visible = false;
}));
return 0;
}
//測(cè)試調(diào)用
private void call()
{
//Func<string, string> funcOne = delegate(string s){ return "fff"; };
object i = 55;
var t = Task<int>.Factory.StartNew(new Func<object, int>(test2), i);
}
//= 下載網(wǎng)站源文件例子 == == == == == == == == == == == ==
//HttpClient 引用System.Net.Http
private async Task< int> test2(object i)
{
this.Invoke(new Action(() =>
{
pictureBox1.Visible = true;
}));
HttpClient client = new HttpClient();
var a = await client.GetAsync("http://www.baidu.com");
Task<string> s = a.Content.ReadAsStringAsync();
MessageBox.Show (s.Result);
//System.Threading.Thread.Sleep(3000);
//MessageBox.Show("hello:"+ i);
this.Invoke(new Action(() =>
{
pictureBox1.Visible = false;
}));
return 0;
}
async private void call()
{
//Func<string, string> funcOne = delegate(string s){ return "fff"; };
object i = 55;
var t = Task<Task<int>>.Factory.StartNew(new Func<object, Task<int>>(test2), i);
}
//----------或者----------
private async void test2()
{
this.Invoke(new Action(() =>
{
pictureBox1.Visible = true;
}));
HttpClient client = new HttpClient();
var a = await client.GetAsync("http://www.baidu.com");
Task<string> s = a.Content.ReadAsStringAsync();
MessageBox.Show (s.Result);
this.Invoke(new Action(() =>
{
pictureBox1.Visible = false;
}));
}
private void call()
{
var t = Task.Run(new Action(test2));
//相當(dāng)于
//Thread th= new Thread(new ThreadStart(test2));
//th.Start();
}
Task啟動(dòng)帶參數(shù)和返回值的函數(shù)任務(wù)
以上就是深入分析C# Task的詳細(xì)內(nèi)容,更多關(guān)于C# Task的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Unity Shader實(shí)現(xiàn)圖形繪制(藍(lán)天白云大海)
這篇文章主要為大家詳細(xì)介紹了Unity Shader實(shí)現(xiàn)圖形繪制,藍(lán)天白云大海,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
c# Invoke和BeginInvoke 區(qū)別分析
這篇文章主要介紹了c# Invoke和BeginInvoke 區(qū)別分析,需要的朋友可以參考下2014-10-10
C# 指針內(nèi)存控制Marshal內(nèi)存數(shù)據(jù)存儲(chǔ)原理分析
這篇文章主要介紹了C# 指針 內(nèi)存控制 Marshal 內(nèi)存數(shù)據(jù)存儲(chǔ)原理分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

