110,473
社区成员
发帖
与我相关
我的任务
分享
th = new Thread(() =>
{
SetResult(Utils.Search(60));
});
th.IsBackground = true;
th.Start();
th.Abort();//终止线程
CancellationTokenSource cts = new CancellationTokenSource();
string res = "";
await Task.Run(() =>
{
timer.Start();
res = Utils.Search(60);
}, cts.Token);
if (!cts.IsCancellationRequested)
{
SetResult(res);
}
CancellationTokenSource cts;
int num = 0;
Dictionary<int, CancellationTokenSource> ctsList = new Dictionary<int, CancellationTokenSource>();
async void SSearch(int num)
{
try
{
string res = await method(cts.Token);
if (ctsList[num].IsCancellationRequested)
{
Item.Add($"测试{num}结果:已取消");
}
else
{
Item.Add($"测试{num}结果:{res}");
}
}
catch (Exception e)
{
Item.Add($"测试{num}异常:" + e.Message);
}
finally
{
timer.Stop();
Info = "等待支付...";
}
}
static async Task Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
//测试一:
try
{
cts.CancelAfter(TimeSpan.FromSeconds(2));//2秒后就取消
string res = await method(cts.Token);
Console.WriteLine($"测试一结果:{res}");
}
catch (Exception e)
{//方法本身需要10秒,上面2秒后取消,会触发一个Canceled异常
Console.WriteLine("测试一异常:" + e.Message);
}
//测试二
try
{
cts = new CancellationTokenSource();
string res = await method(cts.Token);
//不做取消,会正常拿到结果
Console.WriteLine($"测试二结果:{res}");
}
catch (Exception e)
{
Console.WriteLine($"测试二异常:"+e.Message);
}
Console.ReadKey();
}
//异步锁
private static SemaphoreSlim slim = new SemaphoreSlim(1);
static async Task<string> method(CancellationToken cts)
{
await slim.WaitAsync(); //异步加锁
//同步值到异步值封装任务
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
try
{
await Task.Run(() =>
{
string res = test(TimeSpan.FromSeconds(10));
tcs.TrySetResult(res);
slim.Release(); //释放异步锁
}
, cts);
}
catch (Exception e)
{
tcs.TrySetException(e);
}
finally
{
slim.Release();
}
return await tcs.Task;
}
//模拟一个C++同步阻塞调用
static string test(TimeSpan time)
{
Thread.Sleep(time);
return "end";
}
Async Task<string> method(CancellationToken cts )
{
TaskCompletionSource<string>tcs=new TaskCompletionSource<string>();
Task.run( ()=>{
cts.Register(() => { //订阅注销事件
tcs.TrySetCanceled() ; //给一个Canceled信号给tcs,让tcs的task结束,并传递给调用方
Thread.CurrentThread.Abort(); //这句就是结束这个线程,理论上下这句会结束这个线程,同时会引发下面异常,当然我前面也说了,我不知道那边C++的是否能正确处理这种被强制取消的处理,所以前面我其实本不想给你说这种处理方式
});
try
{
string res = Utils.Search(60);
tcs.TrySetResult(res);
}
catch(Exception ex)
{
tcs.TrySetException(ex) //尝试给外面抛个异常,如果是上面注销事件触发的,因为前面已经抛了一个chanceled,所以这里消息其实被抛弃了
}
},cts)
retrun await tcs.Task;
}