.net 4 使用System.Threading.Tasks
.net 4.5以上支持System.Threading.Tasks功能,4.0支持不全,可以通过配置解决
1. Task.Run(), Task.Delay().Wait()
public class TaskEx
{
public static Task Run(Action action)
{
var tcs = new TaskCompletionSource<object>();
new Thread(() => {
try
{
action();
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
})
{ IsBackground = true }.Start();
return tcs.Task;
}
public static Task<TResult> Run<TResult>(Func<TResult> function)
{
var tcs = new TaskCompletionSource<TResult>();
new Thread(() =>
{
try
{
tcs.SetResult(function());
}
catch (Exception ex)
{
tcs.SetException(ex);
}
})
{ IsBackground = true }.Start();
return tcs.Task;
}
public static Task Delay(int milliseconds)
{
var tcs = new TaskCompletionSource<object>();
var timer = new System.Timers.Timer(milliseconds) { AutoReset = false };
timer.Elapsed += delegate { timer.Dispose(); tcs.SetResult(null); };
timer.Start();
return tcs.Task;
}
}
使用方法:
TaskEx.Run(() => MultiIssue()); TaskEx.Delay(10000);
2. async await
报错信息:
Severity Code Description Project File Line Suppression State Warning The primary reference "Microsoft.Threading.Tasks" could not be resolved because it has an indirect dependency on the framework assembly "System.Runtime, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which could not be resolved in the currently targeted framework. ".NETFramework,Version=v4.0". To resolve this problem, either remove the reference "Microsoft.Threading.Tasks" or retarget your application to a framework version which contains "System.Runtime, Version=1.5.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". DataconAutoIssue
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
....
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.6.8.0" newVersion="2.6.8.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
引用DLL

https://files.cnblogs.com/files/itstar/Task4.0DLLs.zip
3. public event EventHandler<string> ScannerMessageReceived;
报错信息:
Severity Code Description Project File Line Suppression State Error CS0311 The type 'string' cannot be used as type parameter 'TEventArgs' in the generic type or method 'EventHandler<TEventArgs>'. There is no implicit reference conversion from 'string' to 'System.EventArgs'. DataconAutoIssue D:\project\E-info\DataconAutoIssue\ScannerTCP.cs 46 Active
4.0写法:
public event Action<object, string> ScannerMessageReceived;
浙公网安备 33010602011771号